/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor. 
 */
package merlion.common.session.stateless;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import merlion.common.entity.*;
import merlion.common.util.*;
import merlion.common.util.exception.NotExistException;
import merlion.crm.slcm.entity.Address;
import merlion.crm.slcm.entity.ContactRecord;
import merlion.crm.slcm.entity.Customer;
import merlion.crm.slcm.entity.MemberDiscountGroup;
import merlion.crm.slcm.entity.OrderDiscountGroup;
import merlion.crm.slcm.entity.SalesLead;
import merlion.crm.slcm.session.SLCSessionBeanLocal;
import merlion.crm.sopm.entity.ItemLine;
import merlion.crm.sopm.entity.PurchaseOrder;
import merlion.crm.sopm.entity.SalesOrder;
import merlion.crm.sopm.entity.SalesQuotation;
import merlion.crm.sopm.session.SOPSessionBeanLocal;
import merlion.frm.bpm.entity.CustomerPaymentRecord;
import merlion.frm.bpm.entity.Invoice;
import merlion.frm.bpm.entity.Receipt;
import merlion.frm.bpm.entity.SupplierInvoice;
import merlion.frm.bpm.session.SalesBPSessionBeanLocal;
import merlion.frm.ccm.entity.CreditAccount;
import merlion.frm.ccm.entity.CreditGroup;
import merlion.mrp.atpm.session.ATPSessionBeanLocal;
import merlion.mrp.pmm.entity.FinishedGood;
import merlion.mrp.pmm.session.ProductManagementSessionLocal;
import merlion.mrp.ppm.entity.BOM;
import merlion.mrp.ppm.entity.IndexNValue;
import merlion.mrp.ppm.entity.IndivForecast;
import merlion.mrp.ppm.entity.MRP;
import merlion.mrp.ppm.entity.Product;
import merlion.mrp.ppm.entity.PublicHoliday;
import merlion.mrp.ppm.entity.SOP;
import merlion.mrp.ppm.entity.SalesForecast;
import merlion.mrp.ppm.session.MRPSessionLocal;
import merlion.mrp.ppm.session.SalesForecastingSessionLocal;
import merlion.mrp.ppm.session.SalesOptPlanningSessionLocal;
import merlion.scm.icm.entity.ProductInventoryRecord;
import merlion.scm.icm.entity.WarehouseLocation;
import merlion.scm.icm.session.InventoryControlSessionBeanLocal;
import merlion.scm.lcm.entity.DeliveryOrder;
import merlion.scm.lcm.entity.PackingOrder;
import merlion.scm.lcm.entity.PickingOrder;
import merlion.scm.lcm.entity.ShippingOrder;
import merlion.scm.lcm.session.LogisticControlSessionBeanLocal;
import merlion.scm.rmpm.entity.GoodsReceipt;
import merlion.scm.rmpm.entity.RawMaterial;
import merlion.scm.rmpm.entity.RawMaterialCase;
import merlion.scm.rmpm.entity.RawMaterialInventoryBatch;
import merlion.scm.rmpm.entity.RawMaterialInventoryRecord;
import merlion.scm.rmpm.entity.RawMaterialItemLine;
import merlion.scm.rmpm.entity.RawMaterialPurchaseOrder;
import merlion.scm.rmpm.entity.RawMaterialSalesOrder;
import merlion.scm.rmpm.entity.RawMaterialSupplyInformation;
import merlion.scm.rmpm.entity.Supplier;
import merlion.scm.rmpm.entity.SupplierContactRecord;
import merlion.scm.rmpm.session.RawMaterialPurchaseSessionBeanLocal;

/**
 *
 * @author Zhang Ying, Zhiqi, Kenneth, Yuwei, Zhu Xin, Zhou Hong
 */
@Stateless
@LocalBean
public class AdminSession {

    @PersistenceContext
    private EntityManager entityManager;
    private ArrayList<MemberDiscountGroup> mdgs = new ArrayList<MemberDiscountGroup>();
    private static final SimpleDateFormat formatter = new SimpleDateFormat("MMMMM dd, yyyy");
    @EJB
    private SOPSessionBeanLocal sopBean;
    @EJB
    private SLCSessionBeanLocal slcBean;
    @EJB
    private LogisticControlSessionBeanLocal lcBean;
    @EJB
    private RawMaterialPurchaseSessionBeanLocal rmpBean;
    @EJB
    private InventoryControlSessionBeanLocal icBean;
    @EJB
    private ProductManagementSessionLocal pmBean;
    @EJB
    private ATPSessionBeanLocal atpBean;
    @EJB
    private SalesForecastingSessionLocal salesForecastSession;
    @EJB
    private SalesOptPlanningSessionLocal sopSession;
    @EJB
    private MRPSessionLocal mrpSession;
    @EJB
    private SalesBPSessionBeanLocal sbpSession;
    @EJB
    private GlobalVariableSessionBeanLocal gvSession;

    public void createTechStaff() {

        createGlobalVariable();
        createPublicHolidays();
        createAccessRights();
        createSecurityRoles();
        createSuperAdmin();
        createTechnicalStaff();
        createSalesExecutives();
        createSalesManagers();
        createSalesVPs();
        createFinanceStaff();
        createSupplyChainStaff();
        createMRPStaff();
        createProducts();
        createMemberDiscountGroup();
        createOrderDiscount();
        createCreditGroup();
        createSalesLead();
        createCustomer1();
        createCustomer2();
        createCustomer3();
        createCustomer4();
        createCustomer5();
        createCustomer6();
        createBOMs();
        createWarehouse();

        // TODO: please don't delete it!! 
        randomizeSalesOrder(100);

        createSuppliers();
        createRawMaterialInventoryRecord();
        createRawMaterialInventory();
        createProductInventoryRecord();
        createProductInventory();
        createIntelligentData(5);
        
        createProductionPlan();

    }

    public void createJunitTestData() {
        createGlobalVariable();
        createTestStaff();
        createTestCreditGroup();
        createCustomerTest();
        createSalesLeadTest();
        createClientTest();
        createCustomerWithNoCa();
        createSalesForecast();
        createProducts();
        createBOMs();
        createSuppliers();
        createWarehouse();
        createProductInventoryRecord();
        createRawMaterialInventoryRecord();
        createRawMaterialInventory();
        createProductInventory();
    }

    private void createGlobalVariable() {

        GlobalVariable gv = new GlobalVariable();
        gv.setGlobalKey(Consts.GLOBAL_CASH_ON_HAND);
        gv.setDoubleValue(8000000D);
        entityManager.merge(gv);

        GlobalVariable gv1 = new GlobalVariable();
        gv1.setGlobalKey(Consts.GLOBAL_SAFETY_CASH);
        gv1.setDoubleValue(500000D);
        entityManager.merge(gv1);

        GlobalVariable gv2 = new GlobalVariable();
        gv2.setGlobalKey(Consts.GLOBAL_TAX_RATE);
        gv2.setDoubleValue(0.07D);
        entityManager.merge(gv2);

        GlobalVariable gv3 = new GlobalVariable();
        gv3.setGlobalKey(Consts.GLOBAL_SPECIAL_DISCOUNT);
        gv3.setDoubleValue(0.05D);
        entityManager.merge(gv3);
    }

    private void testFinancial() {

        long oneDay = (long) (1 * 24 * 60 * 60 * 1000);
        ArrayList<Timestamp> dates = new ArrayList<Timestamp>();
        for (long i = 0; i < 30; i++) {
            Timestamp t = new Timestamp(System.currentTimeMillis() - (i * oneDay));
            dates.add(t);
        }

        ArrayList<Customer> cList = new ArrayList<Customer>(slcBean.getAllCustomer());
        ArrayList<Supplier> lList = new ArrayList<Supplier>(rmpBean.getAllSupplier());

        int x = 0;
        for (Timestamp ts : dates) {
            Invoice i = new Invoice();
            i.setInvoiceDate(ts);
            i.setInvoiceId(sbpSession.generateInvoiceId());
            i.setInvoiceDueDate(new Timestamp(ts.getTime() - (oneDay * 30l)));
            i.setTotal(75000D);
            i.setCustomer(cList.get(0));
            i.setDeliveryOrder(null);
            i.setCustomerPaymentRecord(null);
            x++;
            if (x > 14) {
                break;
            }
            entityManager.merge(i);
        }

        for (int y = 0; y < 30; y += 7) {
            SupplierInvoice si = new SupplierInvoice();
            si.setInvoiceAmount(1200000D);
            si.setDateCreated(dates.get(y));
            si.setInvoiceDueDate(new Timestamp(dates.get(y).getTime() + (oneDay * 30l)));
            si.setItemLines(null);
            si.setRmso(null);
            si.setSupplier(lList.get(0));
            si.setSupplierPaymentRecord(null);
            entityManager.merge(si);
        }

    }

    private void createProductInventory() {

        //get Daily MPS

        ArrayList<Product> products = new ArrayList<Product>(entityManager.createQuery("SELECT p FROM Product p").getResultList());
        for (Product p : products) {
            FinishedGood fg = new FinishedGood();
            fg.setQuantity(600L);
            fg.replaceBatchNoWithAlpha(p.getProductType());
            fg = pmBean.createFinishedGoodsRecord(fg, p);
            entityManager.merge(fg);
        }

    }

    private void createProductInventoryRecord() {

        ArrayList<Product> products = new ArrayList<Product>(entityManager.createQuery("SELECT p FROM Product p").getResultList());
        for (Product p : products) {
            ProductInventoryRecord r = new ProductInventoryRecord();
            r.setProduct(p);
            r.setBalance(0L);
            r.setOptimalStock(1500L);
            r.setReservedQty(0L);
            r.setBatches(new ArrayList<FinishedGood>());
            p.setPir(r);
            entityManager.merge(r);
        }
    }

    private void createRawMaterialInventory() {

        Supplier s = (Supplier) entityManager.createQuery("SELECT s FROM Supplier s").getResultList().get(0);

        // Date of purchase: 02 Nov 2011
        Timestamp purchaseDate = new Timestamp(System.currentTimeMillis());
        purchaseDate.setMonth(10);
        purchaseDate.setYear(2011);
        purchaseDate.setDate(2);

        RawMaterialPurchaseOrder rmpo = new RawMaterialPurchaseOrder();
        rmpo.setAddress(s.getSupplierAddress());
        rmpo.setComments("Purchase for Initial Raw Material Inventory");
        rmpo.setCurrency(Boolean.TRUE);
        rmpo.setHiddenId(purchaseDate);
        // Set Item Lines
        ArrayList<RawMaterial> rList = new ArrayList<RawMaterial>(entityManager.createQuery("SELECT r FROM RawMaterial r").getResultList());
        ArrayList<RawMaterialItemLine> rmils = new ArrayList<RawMaterialItemLine>();
        for (RawMaterial r : rList) {
            RawMaterialSupplyInformation rmis = r.getSupplies().get(0);

            RawMaterialItemLine rmil = new RawMaterialItemLine();
            rmil.setRawMaterialSupplyInformation(rmis);
            rmil.setQty(200L);
            rmil = rmpBean.calculateLine(rmil);
            rmils.add(rmil);
        }
        rmpo.setItemLines(rmils);
        rmpo.setPoDate(purchaseDate);
        rmpo.setPoNum(rmpBean.generatePurchaseOrderNumber());
        rmpo.setRawMaterialRequestForQuotation(null);
        rmpo.setRmso(null);
        rmpo.setSupplier(s);
        rmpo.setUrgent(Boolean.FALSE);
        rmpo = rmpBean.calculatePurchaseOrder(rmpo);

        rmpo = rmpBean.savePurchaseOrder(rmpo);
        entityManager.flush();

        // Receive Sales Order from supplier five days later

        RawMaterialSalesOrder rmso = new RawMaterialSalesOrder();
        rmso.setCurrency(Boolean.TRUE);
        rmso.setGoodsReceipt(null);
        rmso.setInvoice(null);
        rmso.setItemlines(new ArrayList<RawMaterialItemLine>());
        for (RawMaterialItemLine rmil : rmpo.getItemLines()) {
            rmso.getItemlines().add(rmil.clone());
        }
        rmso.setRmpo(rmpo);
        rmso.setSalesOrderDate(new Timestamp(purchaseDate.getTime() + (long) (5 * 24 * 60 * 60 * 1000)));
        rmso.setSalesOrderId("SUPP/SO/1098241");
        rmso.setSupplier(s);
        rmso.setTotal(rmpo.getTotalSGD());
        rmso.setUploadedImage(null);

        rmpo.setRmso(rmso);

        rmso = rmpBean.saveSalesOrder(rmso);
        entityManager.flush();

        //Receive Raw Material Invoice 11 days after purchase order sent, due 15 days after sales order.
        SupplierInvoice si = new SupplierInvoice();
        si.setCurrency(Boolean.TRUE);
        si.setDateCreated(new Timestamp(purchaseDate.getTime() + (long) (11 * 24 * 60 * 60 * 1000)));
        si.setInvoiceAmount(rmso.getTotal());
        si.setInvoiceDueDate(new Timestamp(rmso.getSalesOrderDate().getTime() + (long) (15 * 24 * 60 * 60 * 1000)));
        si.setItemLines(new ArrayList<RawMaterialItemLine>());
        for (RawMaterialItemLine rmil : rmso.getItemlines()) {
            si.getItemLines().add(rmil.clone());
        }
        si.setRmso(rmso);
        si.setSupplier(s);
        si.setSupplierInvoiceNo("SUPP/INV/ 1284114");
        si.setSupplierPaymentRecord(null);
        si.setUploadedImage(null);

        // Receive Goods from Supplier 9 days from purchase order date
        GoodsReceipt gr = new GoodsReceipt();
        gr.setDateReceipt(new Timestamp(purchaseDate.getTime() + (long) (9 * 24 * 60 * 60 * 1000)));
        gr.setGoodsReceiptId("SUPP/GR/10281471");
        gr.setItemlines(new ArrayList<RawMaterialItemLine>());
        for (RawMaterialItemLine rmil : rmso.getItemlines()) {
            gr.getItemlines().add(rmil.clone());
            System.out.println("RMIL: " + rmil.getRawMaterialSupplyInformation().getRawMaterial().getName() + " Qty: " + rmil.getQty());
        }

        gr.setRating(null);
        gr.setRmso(rmso);
        gr.setSupplier(s);

        if (icBean.createGoodsReceipt(gr)) {
            System.out.println("Raw Material Received and Added to Inventory");
        } else {
            System.out.println("Raw Material Purchase Failed");
        }
    }

    private void createRawMaterialInventoryRecord() {

        ArrayList<RawMaterial> rms = new ArrayList<RawMaterial>(entityManager.createQuery("SELECT r FROM RawMaterial r").getResultList());
        for (RawMaterial r : rms) {
            RawMaterialInventoryRecord i = new RawMaterialInventoryRecord();
            i.setRawMaterial(r);
            i.setOptimalStock(200D);
            i.setBalance(0D);
            i.setBatches(new ArrayList<RawMaterialInventoryBatch>());
            entityManager.merge(i);
        }
    }

    private void createIntelligentData(int size) {
        randomizeSalesQuotation(size);
        createPurchaseOrders();
        createSalesOrders();
        createPaymentReceipt();
    }

    public void createSuppliers() {

        ArrayList<RawMaterial> list = new ArrayList<RawMaterial>(entityManager.createQuery("SELECT r FROM RawMaterial r").getResultList());

        Supplier s = new Supplier();
        s.setRawMaterialsSupplied(new ArrayList<RawMaterialSupplyInformation>());
        s.setSupplierAddress(null);
        s.setSupplierId(rmpBean.generateSupplierId());
        s.setSupplierName("Delicious Commodities Pte Ltd");
        s.setRating(3.6);
        s.setActualLeadTime(10.5D);
        for (int k = 0; k < 7; k++) {
            RawMaterialSupplyInformation rm = new RawMaterialSupplyInformation();
            rm.setRawMaterial(list.get(k));
            rm.setUnitPriceSGD(k + (double) 20);
            rm.setUnitPriceUSD(rm.getUnitPriceSGD() / 1.2);
            rm.setUnitLotPriceSGD(rm.getUnitPriceSGD() * list.get(k).getLotSize().doubleValue());
            rm.setUnitLotPriceUSD(rm.getUnitPriceUSD() * list.get(k).getLotSize().doubleValue());
            rm.setSupplier(s);
            s.getRawMaterialsSupplied().add(rm);
            list.get(k).getSupplies().add(rm);
        }
        Address a1 = new Address();
        a1.setAddressLine1("Price Water Cooper House");
        a1.setAddressLine2("38 Water Lane Street");
        a1.setAddressType("Supplier Address");
        a1.setCity("Bangladesh");
        a1.setCountry("India");
        a1.setStateName("Waterlulu");
        a1.setZipCode("344356");
        s.setSupplierAddress(a1);
        SupplierContactRecord scr = new SupplierContactRecord();
        scr.setName("Mr Anderson");
        scr.setJobTitle("Relationship Manager");
        scr.setPhone("+801-1118723113");
        scr.setEmail("is3102m01demo@gmail.com");
        scr.setExecutive(Boolean.TRUE);
        s.getContacts().add(scr);
        entityManager.merge(s);

        Supplier s1 = new Supplier();
        s1.setRawMaterialsSupplied(new ArrayList<RawMaterialSupplyInformation>());
        s1.setSupplierAddress(null);
        s1.setSupplierId(rmpBean.generateSupplierId());
        s1.setSupplierName("Beautiful Powder Corp");
        s1.setRating(2.6);
        s1.setActualLeadTime(16.1D);
        for (int k = 7; k < 12; k++) {
            RawMaterialSupplyInformation rm = new RawMaterialSupplyInformation();
            rm.setUnitPriceSGD(k + (double) 20);
            rm.setUnitPriceUSD(rm.getUnitPriceSGD() / 1.2);
            rm.setUnitLotPriceSGD(rm.getUnitPriceSGD() * list.get(k).getLotSize().doubleValue());
            rm.setUnitLotPriceUSD(rm.getUnitPriceUSD() * list.get(k).getLotSize().doubleValue());
            rm.setRawMaterial(list.get(k));
            rm.setSupplier(s1);
            s1.getRawMaterialsSupplied().add(rm);
            list.get(k).getSupplies().add(rm);
        }
        Address a2 = new Address();
        a2.setAddressLine1("International Powder Building");
        a2.setAddressLine2("88 Alibaba Street");
        a2.setAddressType("Supplier Address");
        a2.setCity("Beijing");
        a2.setCountry("China");
        a2.setStateName("DianXiaoEr");
        a2.setZipCode("344356");
        s1.setSupplierAddress(a2);
        SupplierContactRecord scr2 = new SupplierContactRecord();
        scr2.setName("Jennifer Lee");
        scr2.setJobTitle("Sales Manager");
        scr2.setPhone("+851-638161231");
        scr2.setEmail("jennifer.lee@bpc.com");
        scr2.setExecutive(Boolean.TRUE);
        s1.getContacts().add(scr2);
        entityManager.merge(s1);

        Supplier s2 = new Supplier();
        s2.setRawMaterialsSupplied(new ArrayList<RawMaterialSupplyInformation>());
        s2.setSupplierAddress(null);
        s2.setSupplierId(rmpBean.generateSupplierId());
        s2.setSupplierName("Natural Nuts and Fruits Pte Ltd");
        s2.setRating(4.8);
        s2.setActualLeadTime(7.6D);
        for (int k = 12; k < 23; k++) {
            RawMaterialSupplyInformation rm = new RawMaterialSupplyInformation();
            rm.setUnitPriceSGD(k + (double) 20);
            rm.setUnitPriceUSD(rm.getUnitPriceSGD() / 1.2);
            rm.setUnitLotPriceSGD(rm.getUnitPriceSGD() * list.get(k).getLotSize().doubleValue());
            rm.setUnitLotPriceUSD(rm.getUnitPriceUSD() * list.get(k).getLotSize().doubleValue());
            rm.setRawMaterial(list.get(k));
            rm.setSupplier(s2);
            s2.getRawMaterialsSupplied().add(rm);
            list.get(k).getSupplies().add(rm);
        }
        Address a3 = new Address();
        a3.setAddressLine1("Happy Fruits Valley House");
        a3.setAddressLine2("501 Fruits Farm");
        a3.setAddressType("Supplier Address");
        a3.setCity("Malacca");
        a3.setCountry("Malaysia");
        a3.setStateName("Malacca");
        a3.setZipCode("344356");
        s2.setSupplierAddress(a3);
        SupplierContactRecord scr3 = new SupplierContactRecord();
        scr3.setName("Mr Brown");
        scr3.setJobTitle("King of fruits");
        scr3.setPhone("+60-9876543");
        scr3.setEmail("brown@nnf.com");
        scr3.setExecutive(Boolean.TRUE);
        s2.getContacts().add(scr3);
        entityManager.merge(s2);
    }

    public void createWarehouse() {

        //Create Warehouse Location
        ArrayList<WarehouseLocation> wList = new ArrayList<WarehouseLocation>();
        for (int i = 1; i < 4; i++) {
            // For each warehouse storage area
            for (int j = 1; j < 10; j++) {
                // For each storage row
                for (int k = 1; k < 4; k++) {
                    // For each level
                    for (int l = 1; l < 101; l++) {
                        //100 bin on each level
                        WarehouseLocation w = new WarehouseLocation();
                        w.setBinLocation("S" + i + "R" + j + "L" + k + "B" + l);
                        w.setBinCapacity((double) 100);
                        w.setBatch(null);
                        w.setRmBatch(null);
                        w.setEmptyBin(true);
                        w.setStoredQty(0D);
                        w = entityManager.merge(w);
                        wList.add(w);
                    }
                }
            }
        }
    }

    private void createRawMaterialInvRecords(Timestamp startDate, int days) {

        //Create Warehouse Location
        List<WarehouseLocation> wList = entityManager.createQuery("SELECT w FROM WarehouseLocation w").getResultList();
        ArrayList<WarehouseLocation> wAList = new ArrayList<WarehouseLocation>(wList);

        //Get list of raw materials
        ArrayList<RawMaterial> rmList = new ArrayList<RawMaterial>();
        for (int i = 0; i < 10; i++) {
            RawMaterial r = new RawMaterial();
            r.setLeadtime((long) 2);
            r.setLotSize((long) 100);
            r.setName("Raw Material " + i);
            r = entityManager.merge(r);
            rmList.add(r);
        }

        //Set list of quantities available
        ArrayList<Long> quantities = new ArrayList<Long>();
        for (long x = 250; x < 1500; x += 50) {
            quantities.add(x);
        }

        //Create Raw Materials
        ArrayList<RawMaterialInventoryRecord> rmirList = new ArrayList<RawMaterialInventoryRecord>();
        for (int i = 0; i < rmList.size(); i++) {
            RawMaterialInventoryRecord rmir = new RawMaterialInventoryRecord();
            rmir.setBatches(new ArrayList<RawMaterialInventoryBatch>());
            rmir.setRawMaterial(rmList.get(i));
            //rmir.setOptimalStock((long) 1200);
            //rmir.setBalance((long) (Math.random() * 3500) + 500);
            rmirList.add(rmir);
        }

        Random rand = new Random();
        long oneDay = (long) (1 * 24 * 60 * 60 * 1000);
        long oneMonth = oneDay * 30;
        //Create Batches
        for (int i = 0; i < days; i++) {

            Timestamp currentDate = new Timestamp(startDate.getTime());
            currentDate.setTime(currentDate.getTime() + ((long) oneDay * (long) i));


            for (RawMaterialInventoryRecord r : rmirList) {

                String batchPostfix = "R" + r.getRawMaterial().getName().charAt(r.getRawMaterial().getName().length() - 1);

                String batchNo = currentDate.toString().substring(0, 10);
                batchNo = batchNo.replaceAll("-", "");
                batchNo = batchNo + batchPostfix;

                //Create batch for product inventory record
                RawMaterialInventoryBatch rmib = new RawMaterialInventoryBatch();
                rmib.setBatchNo(batchNo);
                //  rmib.setQuantity(quantities.get(rand.nextInt(quantities.size())));
                rmib.setDateExpired(new Timestamp(currentDate.getTime() + ((long) oneMonth * 12)));

                int available = 0;
                //Create cases for batch
                for (int j = 0; j < rmib.getQuantity(); j++) {
                    RawMaterialCase rmc = new RawMaterialCase();
                    rmc.setCaseNo(batchNo + "-" + (j + 1));
                    rmc.setComment("");
                    rmc.setConsumed(rand.nextBoolean());
                    if (!rmc.getConsumed()) {
                        available++;
                    }
                    rmc.setDateConsumed(new Timestamp(currentDate.getTime() + ((long) oneDay * 3)));
                    rmc.setLocation(wAList.get(rand.nextInt(wAList.size())));
                }
                //rmib.setQuantityAvailable((long) available);
                r.getBatches().add(rmib);
            }
        }

        for (RawMaterialInventoryRecord rmir : rmirList) {
            long balance = 0;
            for (RawMaterialInventoryBatch f : rmir.getBatches()) {
                balance += f.getQuantityAvailable();
            }
            //rmir.setBalance(balance);
            rmir = entityManager.merge(rmir);
        }
    }
    /*
    private void createProductInvRecords(Timestamp startDate, int days) {
    
    //Create Warehouse Location
    List<WarehouseLocation> wList = entityManager.createQuery("SELECT w FROM WarehouseLocation w").getResultList();
    ArrayList<WarehouseLocation> wAList = new ArrayList<WarehouseLocation>(wList);
    
    //Get list of products
    List<Product> pList = entityManager.createQuery("SELECT p FROM Product p").getResultList();
    ArrayList<Product> pAList = new ArrayList<Product>(pList);
    
    //Set list of quantities available
    ArrayList<Long> quantities = new ArrayList<Long>();
    for (long x = 250; x < 1500; x += 50) {
    quantities.add(x);
    }
    
    //Create Product Inventory Records
    ArrayList<ProductInventoryRecord> pirList = new ArrayList<ProductInventoryRecord>();
    for (int i = 0; i < pAList.size(); i++) {
    ProductInventoryRecord pir = new ProductInventoryRecord();
    pir.setBatches(new ArrayList<InventoryBatch>());
    pir.setProduct(pAList.get(i));
    pir.setOptimalStock((long) 1200);
    pir.setBalance((long) (Math.random() * 3500) + 500);
    pirList.add(pir);
    }
    
    Random rand = new Random();
    long oneDay = (long) (1 * 24 * 60 * 60 * 1000);
    long oneMonth = oneDay * 30;
    //Create Batches
    for (int i = 0; i < days; i++) {
    
    Timestamp currentDate = new Timestamp(startDate.getTime());
    currentDate.setTime(currentDate.getTime() + ((long) oneDay * (long) i));
    
    
    for (ProductInventoryRecord p : pirList) {
    
    String batchPostfix = p.getProduct().getProductType();
    if (batchPostfix.equals("Classic Nuts")) {
    batchPostfix = "CN";
    }
    if (batchPostfix.equals("Classic Fruits")) {
    batchPostfix = "CF";
    }
    if (batchPostfix.equals("Premium Chocolate Nuts")) {
    batchPostfix = "PN";
    }
    if (batchPostfix.equals("Premium Redcurrant Fruits")) {
    batchPostfix = "PF";
    }
    String batchNo = currentDate.toString().substring(0, 10);
    batchNo = batchNo.replaceAll("-", "");
    batchNo = batchNo + batchPostfix;
    
    //Create batch for product inventory record
    FinishedGoodInventoryBatch fgib = new FinishedGoodInventoryBatch();
    fgib.setBatchNo(batchNo);
    fgib.setQuantity(quantities.get(rand.nextInt(quantities.size())));
    fgib.setDateManufactured(new Timestamp(currentDate.getTime()));
    fgib.setDateDisplay(new Timestamp(currentDate.getTime() + ((long) oneMonth * 10)));
    fgib.setDatePrintExpired(new Timestamp(currentDate.getTime() + ((long) oneMonth * 11)));
    fgib.setDateExpired(new Timestamp(currentDate.getTime() + ((long) oneMonth * 12)));
    fgib.setBasePrice((long) 2.5);
    fgib.setUnitPrice((long) 4.5);
    fgib.setCases(new ArrayList<ShippingCase>());
    
    int available = 0;
    //Create cases for batch
    for (int j = 0; j < fgib.getQuantity(); j++) {
    ShippingCase sc = new ShippingCase();
    sc.setProduct(p.getProduct());
    sc.setDeliveryOrder(null);
    sc.setProductionDate(fgib.getDateManufactured());
    sc.setCaseNo(batchNo + "-" + (j + 1));
    sc.setComment("");
    sc.setReserved(rand.nextBoolean());
    if (!sc.getReserved()) {
    available++;
    }
    sc.setDateReserved(new Timestamp(currentDate.getTime() + ((long) oneDay * 3)));
    sc.setLocation(wList.get(rand.nextInt(wList.size())));
    fgib.getCases().add(sc);
    }
    fgib.setQuantityAvailable((long) available);
    p.getBatches().add(fgib);
    }
    }
    
    for (ProductInventoryRecord pir : pirList) {
    long balance = 0;
    for (FinishedGoodInventoryBatch f : pir.getBatches()) {
    balance += f.getQuantityAvailable();
    }
    pir.setBalance(balance);
    pir = entityManager.merge(pir);
    }
    }
     */

//    private void createInvoice() {
//
//        // create unpaid invoice
//        Invoice invoice = new Invoice();
//        SalesOrder so = new SalesOrder();
//        DeliveryOrder d = new DeliveryOrder();
//
//        Customer c = (Customer) entityManager.createQuery("SELECT c FROM Customer c").getResultList().get(0);
//        so.setCustomer(c);
//        so.setSalesOrderIdStr(sopBean.generateSalesOrderId());
//        d.setSalesOrder(so);
//        invoice.setDeliveryOrder(d);
//        invoice.setCustomer(c);
//        invoice.setInvoiceId(sbpSession.generateInvoiceId());
//        invoice.setCustomerPaymentRecord(null);
//        invoice.setTotal((double) 9999);
//
//        entityManager.merge(invoice);
//        entityManager.flush();
//
//        // create unpaid supplier invoice
//        SupplierInvoice si = new SupplierInvoice();
//        si.setInvoiceAmount((double) 9999);
//        //si.setSupplier("Supplier Name");
//        si.setSupplierInvoiceNo("Supplier_Inv_ID");
//        si.setSupplierPaymentRecord(null);
//        si.setUploadedImage(null);
//        entityManager.merge(si);
//
//        // create paid invoice
//        Invoice invoice2 = new Invoice();
//        SalesOrder so2 = new SalesOrder();
//        DeliveryOrder d2 = new DeliveryOrder();
//
//        so2.setCustomer(c);
//        so2.setSalesOrderIdStr(sopBean.generateSalesOrderId());
//        d2.setSalesOrder(so2);
//        invoice2.setDeliveryOrder(d2);
//        invoice2.setCustomer(c);
//        invoice2.setInvoiceId(sbpSession.generateInvoiceId());
//
//        CustomerPaymentRecord cpr = new CustomerPaymentRecord();
//        cpr.setAmountDue((double) 88888);
//        cpr.setPaymentAmount((double) 88888);
//        cpr.setInvoice(invoice2);
// 
//        invoice2.setCustomerPaymentRecord(cpr);
//        invoice2.setTotal((double) 88888);
//        invoice2.setPaid(true);
//
//        entityManager.merge(invoice2);
//
//        //create paid supplier invoice
//        SupplierInvoice si2 = new SupplierInvoice();
//        si2.setInvoiceAmount((double) 123123);
//        si2.setSupplierInvoiceNo("Supplier_Inv_ID");
//
//        SupplierPaymentRecord spr = new SupplierPaymentRecord();
//        spr.setPaymentAmount((double) 123123);
//        spr.setSupplierInvoice(si2);
//        //si2.setSupplier("Supplier name");
//        si2.setSupplierPaymentRecord(spr);
//        si2.setUploadedImage(null);
//        entityManager.merge(si2);
//
//    }
    private double roundFourDecimals(double d) {
        DecimalFormat fourDForm = new DecimalFormat("#.####");
        return Double.valueOf(fourDForm.format(d));
    }

    private void randomizeSalesQuotation(int size) {

        // --------------------------- Customer ------------------------------
        ArrayList<Customer> customers = new ArrayList<Customer>(entityManager.createQuery("SELECT c FROM Customer c").getResultList());

        //---------------------------- Product ---------------------------------
        ArrayList<Product> products = new ArrayList<Product>(entityManager.createQuery("SELECT p FROM Product p").getResultList());

        //---------------------------- Qty Size --------------------------------
        ArrayList<Long> quantities = new ArrayList<Long>();
        for (long x = 50, i = 0; x < 151; x += 50, i++) {
            quantities.add(x);
        }
        quantities.add((long) 0);

        //---------------------------- Special discount ------------------------
        ArrayList<Double> sDiscounts = new ArrayList<Double>();
        for (double x = 0.01; x < 0.04; x += 0.01) {
            sDiscounts.add(x);
        }

        // Create randomizer and constants
        Random rand = new Random();
        int cSize = customers.size();
        long oneDay = (long) (1 * 24 * 60 * 60 * 1000);
        long oneMonth = oneDay * 30;

        //---------------------------- Staff -----------------------------------

        // Create random sales quotation based on size
        for (int i = 0; i < size; i++) {

            // Select random customer
            Customer c = customers.get(rand.nextInt(cSize));

            //Create Sales Quotation for sales lead picked, set all primitive data
            SalesQuotation sq = new SalesQuotation();
            sq.setComments("No comments from client");
            sq.setClient(c);
            sq.setCurrency(Boolean.TRUE);
            sq.setCustomerExecutive(c.getCustomerExecutive());
            sq.setFreightOnBoard(Boolean.TRUE);
            sq.setQuotationDate(new Timestamp(System.currentTimeMillis() - (long) (10 * 24 * 60 * 60 * 1000)));
            sq.setRfqNumber("RFQ # from customer");
            sq.setSentToCustomer(Boolean.TRUE);
            sq.setFullShipment(Boolean.TRUE);
            sq.setSqNumber(generateSalesQuotationId());
            sq.setUploadedImage(null);
            sq.setValidityDate(new Timestamp(sq.getQuotationDate().getTime() + (long) (30l * 24l * 60l * 60l * 1000l)));
            System.out.println("valid: " + sq.getQuotationDate().toString());
            c.getSalesQuotations().add(sq);

            // Set itemlines
            double odAmount = (double) 0;
            double mdAmount = (double) 0;
            double sdAmount = (double) 0;
            double originalPrice = (double) 0;
            ArrayList<ItemLine> ilList = new ArrayList<ItemLine>();
            for (Product p : products) {
                ItemLine il = new ItemLine();
                il.setQtyOrderedCase(quantities.get(rand.nextInt(quantities.size())));
                il.setProduct(p);
                if (p.getProductType().contains("Classic")) {
                    il.setQtyOrderedBar(il.getQtyOrderedCase() * (long) 240);
                }
                if (p.getProductType().contains("Premium")) {
                    il.setQtyOrderedBar(il.getQtyOrderedCase() * (long) 200);
                }

                il.setOrderDiscount(slcBean.getOrderDiscountGroup(il).getOrderDiscount());
                if (c instanceof Customer) {
                    try {
                        il.setMemberDiscount(slcBean.getCustomerMemberDiscountGroup(c).getMemberDiscount());
                    } catch (Exception e) {
                    }
                } else {
                    il.setMemberDiscount((double) 0);
                }
                il.setSpecialDiscount(sDiscounts.get(rand.nextInt(sDiscounts.size())));


                if (sq.getClient().getCategory().equals("DirectSale")) {
                    if (il.getProduct().getProductType().contains("Classic")) {
                        il.setUnitPriceSGD(il.getProduct().getDsUnitPrice() * 240);
                        il.setUnitPriceUSD(il.getProduct().getDsUnitPrice() / 1.2 * 240);
                    } else {
                        il.setUnitPriceSGD(roundFourDecimals(il.getProduct().getDsUnitPrice() * 200));
                        il.setUnitPriceUSD(roundFourDecimals(il.getProduct().getDsUnitPrice() / 1.2 * 200));
                    }
                } else { //WholeSale clients
                    if (il.getProduct().getProductType().contains("Classic")) {
                        il.setUnitPriceSGD(roundFourDecimals(il.getProduct().getWsUnitPrice() * 240));
                        il.setUnitPriceUSD(roundFourDecimals(il.getProduct().getWsUnitPrice() / 1.2 * 240));
                    } else {
                        il.setUnitPriceSGD(roundFourDecimals(il.getProduct().getWsUnitPrice() * 200));
                        il.setUnitPriceUSD(roundFourDecimals(il.getProduct().getWsUnitPrice() / 1.2 * 200));
                    }
                }
                System.out.println("WS Unit Price (Bar): " + il.getProduct().getWsUnitPrice());
                System.out.println("DS Unit Price (Bar): " + il.getProduct().getDsUnitPrice());
                System.out.println("ItemLine Unit Price (Case): " + il.getUnitPriceSGD());


                double unitPrice;
                if (sq.getCurrency() == Boolean.TRUE) {
                    //SGD
                    if (il.getProduct().getProductType().equals(Consts.ProductType.BAR_A.getText()) || il.getProduct().getProductType().equals(Consts.ProductType.BAR_B.getText())) {
                        unitPrice = il.getUnitPriceSGD() / 240;
                    } else {
                        unitPrice = il.getUnitPriceSGD() / 200;
                    }
                } else {
                    //USD
                    if (il.getProduct().getProductType().equals(Consts.ProductType.BAR_A.getText()) || il.getProduct().getProductType().equals(Consts.ProductType.BAR_B.getText())) {
                        unitPrice = il.getUnitPriceUSD() / 240;
                    } else {
                        unitPrice = il.getUnitPriceUSD() / 200;
                    }

                }

                double od = il.getOrderDiscount();
                double md = il.getMemberDiscount();
                double sd = il.getSpecialDiscount();

                double quantityBar = il.getQtyOrderedBar();

                System.out.println("before: ----------------------");
                System.out.println("odAmount: " + odAmount);
                System.out.println("sdAmount: " + sdAmount);
                System.out.println("mdAmount: " + mdAmount);
                System.out.println("originalPrice: " + originalPrice);
                System.out.println("quantityBar: " + quantityBar);
                System.out.println("quantityCase: " + il.getQtyOrderedCase());
                System.out.println("unitPrice: " + unitPrice);

                originalPrice += ((double) quantityBar * (double) unitPrice);
                odAmount += ((double) quantityBar * (double) unitPrice * (double) od);
                mdAmount += ((double) quantityBar * (double) unitPrice * ((double) 1.0 - (double) od) * ((double) md));
                sdAmount += ((double) quantityBar * (double) unitPrice * ((double) 1.0 - (double) od) * ((double) 1 - (double) md) * (double) sd);

                double sub = (double) quantityBar * (double) unitPrice * ((double) 1.0 - (double) od) * ((double) 1 - (double) md) * ((double) 1 - (double) sd);
                il.setSubTotal(sub);


                ilList.add(il);

                System.out.println("after: ----------------------");
                System.out.println("odAmount: " + odAmount);
                System.out.println("sdAmount: " + sdAmount);
                System.out.println("mdAmount: " + mdAmount);
                System.out.println("originalPrice: " + originalPrice);
                System.out.println("quantityBar: " + quantityBar);
                System.out.println("quantityCase: " + il.getQtyOrderedCase());
                System.out.println("unitPrice: " + unitPrice);
            }
            sq.setItemLines(ilList);

            // Set Delivery Orders
            ArrayList<DeliveryOrder> dList = new ArrayList<DeliveryOrder>();
            dList.add(new DeliveryOrder());
            if (!sq.getFullShipment()) {
                dList.add(new DeliveryOrder());
            }
            sq.setDeliveryOrders(dList);

            for (DeliveryOrder d : sq.getDeliveryOrders()) {
                d.setActive(Boolean.FALSE);
                d.setInvoice(null);
                d.setItemLines(null);
                d.setLeadTimeTS(new Timestamp(sq.getQuotationDate().getTime() + (oneDay * (long) 30)));
                d.setLeadTime(formatter.format(d.getLeadTimeTS()));

                d.setPackingOrder(null);
                d.setPickingOrder(null);
                d.setPriority(0);
                d.setPurchaseOrder(null);
                d.setSalesOrder(null);
                d.setSalesQuotation(sq);
                d.setShippingAddress(sq.getClient().getShippingAddress().iterator().next());
                d.setShippingOrder(null);
                d.setStatus(null);
                d.setTimeCreated(new Timestamp(System.currentTimeMillis()));
                d.setUrgent(Boolean.FALSE);

                ArrayList<ItemLine> dilList = new ArrayList<ItemLine>();
                ArrayList<ItemLine> totaliList = new ArrayList<ItemLine>(sq.getItemLines());
                for (int x = 0; x < 4; x++) {
                    ItemLine il = totaliList.get(x).clone();
                    dilList.add(il);
                }
                d.setItemLines(dilList);
                d.setMemberDiscount(mdAmount);
                d.setOrderDiscount(odAmount);
                d.setSpecialDiscount(sdAmount);
                d.setSubtotal(originalPrice);
                d.setTotal(originalPrice - mdAmount - odAmount - sdAmount);

                d.setIndicativeLeadTimeTS(atpBean.getIndicativeLeadTimeForRFQ(d));
                if (d.getIndicativeLeadTimeTS() != null) {
                    d.setIndicativeLeadTime(formatter.format(d.getIndicativeLeadTimeTS()));
                } else {
                    d.setIndicativeLeadTime("Not able to fulfill");
                }
            }
            sq.setOrderDiscount(odAmount);
            sq.setMemberDiscount(mdAmount);
            sq.setSpecialDiscount(sdAmount);
            sq.setSubtotal(originalPrice);
            sq.setTotal(originalPrice - odAmount - mdAmount - sdAmount);

            entityManager.merge(sq);
        }
    }

    private void createPurchaseOrders() {

        //Get list of sales quotation
        ArrayList<SalesQuotation> sqList = new ArrayList<SalesQuotation>(sopBean.getAllSalesQuotation());

        // For 100% of sales quotations available, create purchase order for each sales quotation

        for (int i = 0; i < (int) ((double) sqList.size() * 1); i++) {

            SalesQuotation sq = sqList.get(i);

            if (sq.getClient() instanceof Customer) {

                Customer c = null;
                try {
                    c = slcBean.getCustomerByClientId(sq.getClient().getClientId());
                } catch (NotExistException ex) {
                    Logger.getLogger(AdminSession.class.getName()).log(Level.SEVERE, null, ex);
                }

                PurchaseOrder po = new PurchaseOrder();

                //Set po attributes
                po.setComments("No comments from customer");
                po.setCurrency(Boolean.TRUE);
                po.setCustomer(c);
                ArrayList<Staff> staffs = new ArrayList<Staff>(c.getStaffs());
                Staff ce = null;
                for (Staff s : staffs) {
                    for (SecurityRole r : s.getSecurityRoles()) {
                        if (r.getRoleName().equals(Consts.SALES_EXECUTIVE_ROLE)) {
                            ce = s;
                        }
                    }
                }
                po.setCustomerExecutive(ce);
                po.setDateStr(sq.getDateStr());
                po.setDeliveryOrders(new ArrayList<DeliveryOrder>());

                GlobalVariable tax = gvSession.getGlobalVariableByKey(Consts.GLOBAL_TAX_RATE);
                for (DeliveryOrder d : sq.getDeliveryOrders()) {
                    d = d.clone();
                    d.setTax((d.getSubtotal() - d.getMemberDiscount() - d.getOrderDiscount() - d.getSpecialDiscount()) * tax.getDoubleValue().doubleValue());
                    d.setTotal(d.getSubtotal() - d.getMemberDiscount() - d.getOrderDiscount() - d.getSpecialDiscount() + d.getTax());
                    d.setIndicativeLeadTimeTS(new Timestamp(System.currentTimeMillis() + (long) (8 * 60 * 60 * 1000)));
                    d.setPurchaseOrder(po);
                    po.getDeliveryOrders().add(d);
                }
                po.setFreightOnBoard(sq.getFreightOnBoard());
                po.setFullShipment(sq.getFullShipment());
                po.setItemLines(new ArrayList<ItemLine>());
                for (ItemLine il : sq.getItemLines()) {
                    il = il.clone();
                    po.getItemLines().add(il);
                }
                po.setMemberDiscount(sq.getMemberDiscount());
                po.setOrderDiscount(sq.getOrderDiscount());
                po.setPaymentMode(Boolean.TRUE);
                po.setPoNumber("PO" + i);
                po.setPurchaseOrderDate(new Timestamp(System.currentTimeMillis()));
                po.setPurchaseOrderStatus(Boolean.TRUE);
                po.setSalesOrder(null);
                po.setSalesQuotation(sq);
                po.setSpecialDiscount(sq.getSpecialDiscount());
                po.setSubtotal(sq.getSubtotal());
                po.setTaxRate((double) tax.getDoubleValue());
                po.setTax(po.getTaxRate() * (po.getSubtotal() - po.getMemberDiscount() - po.getOrderDiscount() - po.getSpecialDiscount()));
                po.setTotal(po.getSubtotal() - po.getMemberDiscount() - po.getOrderDiscount() - po.getSpecialDiscount() + po.getTax());
                po.setUploadedImage(null);

                po = entityManager.merge(po);
            }
        }
    }

    private void createSalesOrders() {
        System.out.println("Start 1");
        entityManager.flush();
        //Get list of purchase order
        ArrayList<PurchaseOrder> poList = new ArrayList<PurchaseOrder>(sopBean.getAllPurchaseOrders());

        //List of Sales Order Status
        ArrayList<String> soStatus = new ArrayList<String>();
        //soStatus.add("CreditChecking");
        //soStatus.add("ATPChecking");
        //soStatus.add("Completed");
        soStatus.add(Consts.ORDER_WAITFORCIA);

        //Randomizer
        Random rand = new Random();

        //For all purchase order, sales order will be created
        for (int i = 0; i < poList.size(); i++) {
            PurchaseOrder po = poList.get(i);

            SalesOrder so = new SalesOrder();
            so.setCancelled(Boolean.FALSE);
            so.setComments("No comments from client");
            so.setCurrency(po.getCurrency());
            so.setCustomer(po.getCustomer());
            so.setCustomerExecutive(po.getCustomerExecutive());
            so.setDateStr(po.getDateStr());
            so.setDeliveryOrders(new ArrayList<DeliveryOrder>());
            for (DeliveryOrder d : po.getDeliveryOrders()) {
                d = d.clone();
                d.setSalesOrder(so);
                d.setActive(Boolean.TRUE);
                d.setIndicativeLeadTimeTS(new Timestamp(new Date().getTime()));
                d.setIndicativeLeadTime(convertToDateFormat(d.getIndicativeLeadTimeTS()));
                d.setLeadTimeTS(new Timestamp(new Date().getTime()));
                d.setLeadTime(convertToDateFormat(d.getLeadTimeTS()));
                d.setStatus(Consts.LOGISTIC_DELIVERYORDER_QUEUING);
                d.setDeliveryOrderIdStr(lcBean.generateDeliveryOrderId());
                so.getDeliveryOrders().add(d);
            }
            so.setFreightOnBoard(po.getFreightOnBoard());
            so.setFullShipment(po.getFullShipment());
            so.setItemLines(new ArrayList<ItemLine>());
            for (ItemLine il : po.getItemLines()) {
                il = il.clone();
                so.getItemLines().add(il);
            }
            so.setLeadTime(null);
            so.setMemberDiscount(po.getMemberDiscount());
            so.setOrderDiscount(po.getOrderDiscount());
            so.setPaymentMode(po.getPaymentMode());
            so.setPromotion(rand.nextBoolean());
            so.setPurchaseOrder(po);
            po.setSalesOrder(so);
            so.setSalesOrderDate(new Timestamp(System.currentTimeMillis()));
            System.out.println("********** before generateSalesOrderId");
            so.setSalesOrderIdStr(sopBean.generateSalesOrderId());
            System.out.println("********** after generateSalesOrderId");
            so.setSalesOrderStatus(soStatus.get(rand.nextInt(soStatus.size())));
            so.setShipDate(null);
            so.setSpecialDiscount(po.getSpecialDiscount());
            so.setSubtotal(po.getSubtotal());
            so.setTax(po.getTax());
            so.setTotal(po.getTotal());
            so = entityManager.merge(so);

            entityManager.flush();

            System.out.println("Admin Session 975");
            System.out.println(so.getPurchaseOrder().getPoNumber());

        }

        //Create Invoice for all deliveryOrder
        List<DeliveryOrder> dos = lcBean.getAllDeliveryOrder();
        long oneDay = (long) (1 * 24 * 60 * 60 * 1000);
        for (int i = 0; i < dos.size(); i++) {
            if (dos.get(i).getSalesOrder() == null || dos.get(i).getSalesOrder().getPurchaseOrder() == null) {
            } else {
                Invoice inv = new Invoice();
                inv.setCashInAdvance(Boolean.TRUE);
                inv.setCustomer(dos.get(i).getSalesOrder().getCustomer());
                inv.setCustomerPaymentRecord(null);
                inv.setDeliveryOrder(dos.get(i));
                inv.setInvoiceDate(new Timestamp(new Timestamp(new Date().getTime()).getTime() - 30 * oneDay));
                inv.setInvoiceDateStr(convertToDateFormat(inv.getInvoiceDate()));
                inv.setInvoiceDueDate(new Timestamp(inv.getInvoiceDate().getTime() + 30 * oneDay));
                inv.setInvoiceId(sbpSession.generateInvoiceId());
                inv.setPaid(i % 2 == 0 ? true : false);
                inv.setSubtotal(dos.get(i).getSubtotal());
                inv.setTax(dos.get(i).getTax());
                inv.setTotal(dos.get(i).getTotal());
                inv.setPoNumber(inv.getDeliveryOrder().getSalesOrder().getPurchaseOrder().getPoNumber());
                dos.get(i).setInvoice(inv);

                entityManager.merge(inv);
                entityManager.flush();
            }
        }
    }

    public void createPaymentReceipt() {

        ArrayList<Invoice> invoices = new ArrayList<Invoice>(sbpSession.getAllInvoice());

        for (Invoice i : invoices) {
            if (i.isPaid()) {

                //Create customer payment record
                CustomerPaymentRecord cpr = new CustomerPaymentRecord();
                cpr.setAmountDue(i.getTotal());
                cpr.setCashInAdvance(i.getCashInAdvance());
                cpr.setCustomerPaymentRecordId(sbpSession.generateCustomerPaymentRecordId());
                cpr.setInvoice(i);
                i.setCustomerPaymentRecord(cpr);
                cpr.setPaymentAmount(i.getTotal());
                cpr.setPaymentMethod("Cash");
                cpr.setPaymentDate(i.getInvoiceDueDate());
                cpr.setPaymentReference(null);
                cpr.setRealPayment(Boolean.FALSE);
                cpr.setRefunded(Boolean.FALSE);
                cpr = entityManager.merge(cpr);
                //Create receipt
                Receipt r = new Receipt();
                r.setCustomerPaymentRecord(cpr);
                r.setDeliveryOrder(cpr.getInvoice().getDeliveryOrder());
                r.setFinanceAccountant(cpr.getInvoice().getDeliveryOrder().getSalesOrder().getCustomer().getFinanceStaff().getFullName());
                r.setReceiptDate(cpr.getPaymentDate());
                r.setReceiptDateStr(r.getReceiptDate().toString());
                r.setReceiptId(sbpSession.generateReceiptId());

                entityManager.merge(r);

                //Set Sales order status
                SalesOrder so = i.getDeliveryOrder().getSalesOrder();
                so.setSalesOrderStatus(Consts.ORDER_ATPCHECKING);

                //Check ATP
                DeliveryOrder d = i.getDeliveryOrder();
                String leadTime = atpBean.getConfirmedLeadTime(d, d.getIndicativeLeadTimeTS());
                d = lcBean.getDeliveryOrderById(d.getId());
                d.setLeadTime(leadTime);
                d = lcBean.saveDeliveryOrder(d);

                //If ATP available (assume always available),
                //Sales Order set status from "WAITING CONFIRMATION" to "FULFILLING", then logistics
                so.setSalesOrderStatus(Consts.ORDER_FULFILLING);
                so = entityManager.merge(so);

                //lcBean.generateLogisticControlOrders(d);
                //d = lcBean.getDeliveryOrderById(d.getId());
            }
        }
    }

    public void createLogisticsDocuments() {

        //Get all Delivery Orders from confirmed sales order
        ArrayList<DeliveryOrder> dList = new ArrayList<DeliveryOrder>(lcBean.getConfirmedOrderList());

        //For each Delivery Order, generate logistics document
        for (DeliveryOrder d : dList) {
            d.setStatus("Picking");

            //Picking Order
            PickingOrder pick = new PickingOrder();
            pick.setDeliveryOrder(d);
            d.setPickingOrder(pick);
            pick.setStatus(false);
            pick.setLogisticItemLines(null);
            pick.setPickingOrderDate(new Timestamp(System.currentTimeMillis()));
            pick.setPickingOrderId("TEST_PICK_ID");

            //Packing Order
            PackingOrder pack = new PackingOrder();
            pack.setDeliveryOrder(d);
            d.setPackingOrder(pack);
            pack.setDone(false);
            pack.setLogisticItemLines(null);
            pack.setPackingOrderDate(new Timestamp(System.currentTimeMillis()));
            pack.setPackingOrderId("TEST_PACK_ID");

            //Shipping Order
            ShippingOrder ship = new ShippingOrder();
            ship.setDeliveryOrder(d);
            d.setShippingOrder(ship);
            ship.setDone(false);
            ship.setWeight((double) 12);
            ship.setCarrier("UPS");
            ship.setInvoiced(false);
            ship.setLogisticItemLines(null);
            ship.setShippingOrderDate(new Timestamp(System.currentTimeMillis()));
            ship.setShippingOrderId("TEST_SHIP_ID");
        }
    }

    private String generateSalesOrderId() {
        //Get date YYYYMMDD
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String frontId = sdf.format(cal.getTime());

        //Query SalesOrder table, anything like 'yyMMdd'
        Query query = entityManager.createQuery("SELECT s FROM SalesOrder s WHERE s.salesOrderIdStr LIKE :p1");
        query.setParameter("p1", "%" + frontId + "%");

        //Get result size
        int size = query.getResultList().size() + 1;
        String backId = String.format("%04d", size);

        //Set new ID to 'YYYYMMDD' + 'size + 1'
        String id = "SO" + frontId + "/" + backId;
        //return id
        return id;
    }

    private String generateSalesQuotationId() {

        //Get date YYYYMMDD
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        String frontId = sdf.format(cal.getTime());

        //Query Saleslead table, anything like 'yyMMdd'
        Query query = entityManager.createQuery("SELECT s FROM SalesQuotation s WHERE s.sqNumber LIKE :p1");
        query.setParameter("p1", "%" + frontId + "%");

        //Get result size
        int size = query.getResultList().size() + 1;
        String backId = String.format("%04d", size);

        //Set new ID to 'YYYYMMDD' + 'size + 1'
        String id = "SQ" + frontId + "/" + backId;
        //return id
        return id;
    }

    private void createAccessRights() {
        // access right for tech staff
        AccessRight accessRight1 = new AccessRight();
        accessRight1.create(Consts.CREATE_ROLE, Consts.CREATE_ROLE_PATH, Consts.CREATE_ROLE_CATEGORY);
        entityManager.merge(accessRight1);
        AccessRight accessRight2 = new AccessRight();
        accessRight2.create(Consts.DELETE_ROLE, Consts.DELETE_ROLE_PATH, Consts.DELETE_ROLE_CATEGORY);
        entityManager.merge(accessRight2);
        AccessRight accessRight3 = new AccessRight();
        accessRight3.create(Consts.EDIT_ROLE, Consts.EDIT_ROLE_PATH, Consts.EDIT_ROLE_CATEGORY);
        entityManager.merge(accessRight3);
        AccessRight accessRight4 = new AccessRight();
        accessRight4.create(Consts.VIEW_ROLE, Consts.VIEW_ROLE_PATH, Consts.VIEW_ROLE_CATEGORY);
        entityManager.merge(accessRight4);
        AccessRight accessRight5 = new AccessRight();
        accessRight5.create(Consts.CREATE_SYSTEM_USER_ACCOUNT, Consts.CREATE_SYSTEM_USER_ACCOUNT_PATH, Consts.CREATE_SYSTEM_USER_ACCOUNT_CATEGORY);
        entityManager.merge(accessRight5);
        AccessRight accessRight6 = new AccessRight();
        accessRight6.create(Consts.MANAGE_SYSTEM_USER_ACCOUNT, Consts.MANAGE_SYSTEM_USER_ACCOUNT_PATH, Consts.MANAGE_SYSTEM_USER_ACCOUNT_CATEGORY);
        entityManager.merge(accessRight6);
        AccessRight accessRight7 = new AccessRight();
        accessRight7.create(Consts.ANNOUCEMENT_CREATE, Consts.ANNOUCEMENT_CREATE_PATH, Consts.ANNOUCEMENT_CREATE_CATEGORY);
        entityManager.merge(accessRight7);
        AccessRight accessRight8 = new AccessRight();
        accessRight8.create(Consts.ANNOUCEMENT_MANAGE, Consts.ANNOUCEMENT_MANAGE_PATH, Consts.ANNOUCEMENT_MANAGE_CATEGORY);
        entityManager.merge(accessRight8);
        AccessRight accessRight9 = new AccessRight();
        accessRight9.create(Consts.LOGGING_LOGS_VIEW, Consts.LOGGING_LOGS_VIEW_PATH, Consts.LOGGING_LOGS_VIEW_CATEGORY);
        entityManager.merge(accessRight9);
        AccessRight accessRight10 = new AccessRight();
        accessRight10.create(Consts.VIEW_JOB_LIST_ONE_DEP, Consts.VIEW_JOB_LIST_ONE_DEP_PATH, Consts.VIEW_JOB_LIST_ONE_DEP_CATEGORY);
        entityManager.merge(accessRight10);

        // access right for sales executive
        AccessRight accessRight11 = new AccessRight();
        accessRight11.create(Consts.CREATE_SALES_INQUIRY, Consts.CREATE_SALES_INQUIRY_PATH, Consts.CREATE_SALES_INQUIRY_CATEGORY);
        entityManager.merge(accessRight11);
        AccessRight accessRight12 = new AccessRight();
        accessRight12.create(Consts.VIEW_SALES_INQUIRY, Consts.VIEW_SALES_INQUIRY_PATH, Consts.VIEW_SALES_INQUIRY_CATEGORY);
        entityManager.merge(accessRight12);
        AccessRight accessRight13 = new AccessRight();
        accessRight13.create(Consts.CREATE_SALES_QUOTATION, Consts.CREATE_SALES_QUOTATION_PATH, Consts.CREATE_SALES_QUOTATION_CATEGORY);
        entityManager.merge(accessRight13);
        AccessRight accessRight14 = new AccessRight();
        accessRight14.create(Consts.VIEW_SALES_QUOTATION, Consts.VIEW_SALES_QUOTATION_PATH, Consts.VIEW_SALES_QUOTATION_CATEGORY);
        entityManager.merge(accessRight14);
        AccessRight accessRight15 = new AccessRight();
        accessRight15.create(Consts.CREATE_PURCHASE_ORDER, Consts.CREATE_PURCHASE_ORDER_PATH, Consts.CREATE_PURCHASE_ORDER_CATEGORY);
        entityManager.merge(accessRight15);
        AccessRight accessRight16 = new AccessRight();
        accessRight16.create(Consts.VIEW_PURCHASE_ORDER, Consts.VIEW_PURCHASE_ORDER_PATH, Consts.VIEW_PURCHASE_ORDER_CATEGORY);
        entityManager.merge(accessRight16);
        AccessRight accessRight17 = new AccessRight();
        accessRight17.create(Consts.CREATE_SALES_ORDER, Consts.CREATE_SALES_ORDER_PATH, Consts.CREATE_SALES_ORDER_CATEGORY);
        entityManager.merge(accessRight17);
        AccessRight accessRight18 = new AccessRight();
        accessRight18.create(Consts.VIEW_SALES_ORDER, Consts.VIEW_SALES_ORDER_PATH, Consts.VIEW_SALES_ORDER_CATEGORY);
        entityManager.merge(accessRight18);
        AccessRight accessRight23 = new AccessRight();
        accessRight23.create(Consts.VIEW_SALES_FIGURE, Consts.VIEW_SALES_FIGURE_PATH, Consts.VIEW_SALES_FIGURE_CATEGORY);
        entityManager.merge(accessRight23);

        //SLC
        AccessRight accessRight19 = new AccessRight();
        accessRight19.create(Consts.VIEW_ALL_SALESLEAD, Consts.VIEW_ALL_SALESLEAD_PATH, Consts.VIEW_ALL_SALESLEAD_CATEGORY);
        entityManager.merge(accessRight19);
        AccessRight accessRight20 = new AccessRight();
        accessRight20.create(Consts.CREATE_SALESLEAD, Consts.CREATE_SALESLEAD_PATH, Consts.CREATE_SALESLEAD_CATEGORY);
        entityManager.merge(accessRight20);
        AccessRight accessRight21 = new AccessRight();
        accessRight21.create(Consts.VIEW_ALL_CUSTOMER, Consts.VIEW_ALL_CUSTOMER_PATH, Consts.VIEW_ALL_CUSTOMER_CATEGORY);
        entityManager.merge(accessRight21);
        AccessRight accessRight22 = new AccessRight();
        accessRight22.create(Consts.CREATE_CUSTOMER, Consts.CREATE_CUSTOMER_PATH, Consts.CREATE_CUSTOMER_CATEGORY);
        entityManager.merge(accessRight22);
        AccessRight accessRight24 = new AccessRight();
        accessRight24.create(Consts.VIEW_ORDER_DISCOUNT_GROUP, Consts.VIEW_ORDER_DISCOUNT_GROUP_PATH, Consts.VIEW_ORDER_DISCOUNT_GROUP_CATEGORY);
        entityManager.merge(accessRight24);
        AccessRight accessRight25 = new AccessRight();
        accessRight25.create(Consts.MANAGE_ORDER_DISCOUNT_GROUP, Consts.MANAGE_ORDER_DISCOUNT_GROUP_PATH, Consts.MANAGE_ORDER_DISCOUNT_GROUP_CATEGORY);
        entityManager.merge(accessRight25);
        AccessRight accessRight26 = new AccessRight();
        accessRight26.create(Consts.VIEW_MEMBER_DISCOUNT_GROUP, Consts.VIEW_MEMBER_DISCOUNT_GROUP_PATH, Consts.VIEW_MEMBER_DISCOUNT_GROUP_CATEGORY);
        entityManager.merge(accessRight26);
        AccessRight accessRight27 = new AccessRight();
        accessRight27.create(Consts.MANAGE_MEMBER_DISCOUNT_GROUP, Consts.MANAGE_MEMBER_DISCOUNT_GROUP_PATH, Consts.MANAGE_MEMBER_DISCOUNT_GROUP_CATEGORY);
        entityManager.merge(accessRight27);
        AccessRight accessRight28 = new AccessRight();
        accessRight28.create(Consts.MANAGE_SALES_PRICE, Consts.MANAGE_SALES_PRICE_PATH, Consts.MANAGE_SALES_PRICE_CATEGORY);
        entityManager.merge(accessRight28);
        AccessRight accessRight29 = new AccessRight();
        accessRight29.create(Consts.VIEW_ANALYTICS_CLIENT, Consts.VIEW_ANALYTICS_CLIENT_PATH, Consts.VIEW_ANALYTICS_CLIENT_CATEGORY);
        entityManager.merge(accessRight29);

        // for MRP
        AccessRight accessRight30 = new AccessRight();
        accessRight30.create(Consts.CREATE_SALES_FORECAST, Consts.CREATE_SALES_FORECAST_PATH, Consts.CREATE_SALES_FORECAST_CATEGORY);
        entityManager.merge(accessRight30);
        AccessRight accessRight51 = new AccessRight();
        accessRight51.create(Consts.VIEW_SALES_FORECAST, Consts.VIEW_SALES_FORECAST_PATH, Consts.VIEW_SALES_FORECAST_CATEGORY);
        entityManager.merge(accessRight51);
        AccessRight accessRight52 = new AccessRight();
        accessRight52.create(Consts.EDIT_SALES_FORECAST, Consts.EDIT_SALES_FORECAST_PATH, Consts.EDIT_SALES_FORECAST_CATEGORY);
        entityManager.merge(accessRight52);
        AccessRight accessRight53 = new AccessRight();
        accessRight53.create(Consts.CREATE_MRP_SOP, Consts.CREATE_MRP_SOP_PATH, Consts.CREATE_MRP_SOP_CATEGORY);
        entityManager.merge(accessRight53);
        AccessRight accessRight54 = new AccessRight();
        accessRight54.create(Consts.VIEW_MRP_SOP, Consts.VIEW_MRP_SOP_PATH, Consts.VIEW_MRP_SOP_CATEGORY);
        entityManager.merge(accessRight54);
        AccessRight accessRight55 = new AccessRight();
        accessRight55.create(Consts.EDIT_MRP_SOP, Consts.EDIT_MRP_SOP_PATH, Consts.EDIT_MRP_SOP_CATEGORY);
        entityManager.merge(accessRight55);
        //TODO: comment out create daily
//        AccessRight accessRight56 = new AccessRight();
//        accessRight56.create(Consts.CREATE_DAILY_MPS, Consts.CREATE_DAILY_MPS_PATH, Consts.CREATE_DAILY_MPS_CATEGORY);
//        entityManager.merge(accessRight56);
        AccessRight accessRight57 = new AccessRight();
        accessRight57.create(Consts.VIEW_DAILY_MPS, Consts.VIEW_DAILY_MPS_PATH, Consts.VIEW_DAILY_MPS_CATEGORY);
        entityManager.merge(accessRight57);
        AccessRight accessRight58 = new AccessRight();
        accessRight58.create(Consts.EDIT_DAILY_MPS, Consts.EDIT_DAILY_MPS_PATH, Consts.EDIT_DAILY_MPS_CATEGORY);
        entityManager.merge(accessRight58);
        AccessRight accessRight59 = new AccessRight();
        accessRight59.create(Consts.VIEW_WEEKLY_MPS, Consts.VIEW_WEEKLY_MPS_PATH, Consts.VIEW_WEEKLY_MPS_CATEGORY);
        entityManager.merge(accessRight59);

        AccessRight accessRight70 = new AccessRight();
        accessRight70.create(Consts.CREATE_MRP_MRP, Consts.CREATE_MRP_MRP_PATH, Consts.CREATE_MRP_MRP_CATEGORY);
        entityManager.merge(accessRight70);
        AccessRight accessRight71 = new AccessRight();
        accessRight71.create(Consts.VIEW_MRP_MRP, Consts.VIEW_MRP_MRP_PATH, Consts.VIEW_MRP_MRP_CATEGORY);
        entityManager.merge(accessRight71);
        AccessRight accessRight72 = new AccessRight();
        accessRight72.create(Consts.EDIT_MRP_MRP, Consts.EDIT_MRP_MRP_PATH, Consts.EDIT_MRP_MRP_CATEGORY);
        entityManager.merge(accessRight72);
        AccessRight accessRight73 = new AccessRight();
        accessRight73.create(Consts.SIMULATE_FOR_RFQ, Consts.SIMULATE_FOR_RFQ_PATH, Consts.SIMULATE_FOR_RFQ_CATEGORY);
        entityManager.merge(accessRight73);
        AccessRight accessRight74 = new AccessRight();
        accessRight74.create(Consts.SIMULATE_FOR_SO, Consts.SIMULATE_FOR_SO_PATH, Consts.SIMULATE_FOR_SO_CATEGORY);
        entityManager.merge(accessRight74);
        AccessRight accessRight75 = new AccessRight();
        accessRight75.create(Consts.VIEW_BACKORDER, Consts.VIEW_BACKORDER_PATH, Consts.VIEW_BACKORDER_CATEGORY);
        entityManager.merge(accessRight75);
        AccessRight accessRight76 = new AccessRight();
        accessRight76.create(Consts.VIEW_DOCUMENT_FLOW, Consts.VIEW_DOCUMENT_FLOW_PATH, Consts.VIEW_DOCUMENT_FLOW_CATEGORY);
        entityManager.merge(accessRight76);

        AccessRight accessRight39 = new AccessRight();
        accessRight39.create(Consts.MANAGE_BASE_PRICE, Consts.MANAGE_BASE_PRICE_PATH, Consts.MANAGE_BASE_PRICE_CATEGORY);
        entityManager.merge(accessRight39);

        AccessRight accessRight40 = new AccessRight();
        accessRight40.create(Consts.MANAGE_FINISHED_GOODS, Consts.MANAGE_FINISHED_GOODS_PATH, Consts.MANAGE_FINISHED_GOODS_CATEGORY);
        entityManager.merge(accessRight40);

        //Access Right for Finance
        AccessRight accessRight31 = new AccessRight();
        accessRight31.create(Consts.CREATE_CREDIT_ACCOUNT, Consts.CREATE_CREDIT_ACCOUNT_PATH, Consts.CREATE_CREDIT_ACCOUNT_CATEGORY);
        entityManager.merge(accessRight31);
        AccessRight accessRight32 = new AccessRight();
        accessRight32.create(Consts.VIEW_CREDIT_ACCOUNT, Consts.VIEW_CREDIT_ACCOUNT_PATH, Consts.VIEW_CREDIT_ACCOUNT_CATEGORY);
        entityManager.merge(accessRight32);
        AccessRight accessRight33 = new AccessRight();
        accessRight33.create(Consts.VIEW_CREDIT_GROUP, Consts.VIEW_CREDIT_GROUP_PATH, Consts.VIEW_CREDIT_GROUP_CATEGORY);
        entityManager.merge(accessRight33);
        AccessRight accessRight34 = new AccessRight();
        accessRight34.create(Consts.MANAGE_CREDIT_GROUP, Consts.MANAGE_CREDIT_GROUP_PATH, Consts.MANAGE_CREDIT_GROUP_CATEGORY);
        entityManager.merge(accessRight34);
        AccessRight accessRight35 = new AccessRight();
        accessRight35.create(Consts.CREATE_CREDIT_GROUP, Consts.CREATE_CREDIT_GROUP_PATH, Consts.CREATE_CREDIT_GROUP_CATEGORY);
        entityManager.merge(accessRight35);
        AccessRight accessRight36 = new AccessRight();
        accessRight36.create(Consts.CREATE_SALES_INVOICE, Consts.CREATE_SALES_INVOICE_PATH, Consts.CREATE_SALES_INVOICE_CATEGORY);
        entityManager.merge(accessRight36);
        AccessRight accessRight37 = new AccessRight();
        accessRight37.create(Consts.VIEW_SALES_INVOICE, Consts.VIEW_SALES_INVOICE_PATH, Consts.VIEW_SALES_INVOICE_CATEGORY);
        entityManager.merge(accessRight37);
        AccessRight accessRight38 = new AccessRight();
        accessRight38.create(Consts.CREATE_CUSTOMER_PAYMENT_RECORD, Consts.CREATE_CUSTOMER_PAYMENT_RECORD_PATH, Consts.CREATE_CUSTOMER_PAYMENT_RECORD_CATEGORY);
        entityManager.merge(accessRight38);
        AccessRight accessRight47 = new AccessRight();
        accessRight47.create(Consts.VIEW_CUSTOMER_PAYMENT_RECORD, Consts.VIEW_CUSTOMER_PAYMENT_RECORD_PATH, Consts.VIEW_CUSTOMER_PAYMENT_RECORD_CATEGORY);
        entityManager.merge(accessRight47);
        AccessRight accessRight48 = new AccessRight();
        accessRight48.create(Consts.VIEW_RECEIPT, Consts.VIEW_RECEIPT_PATH, Consts.VIEW_RECEIPT_CATEGORY);
        entityManager.merge(accessRight48);
        AccessRight accessRight41 = new AccessRight();
        accessRight41.create(Consts.STORE_SUPPLIER_INVOICE, Consts.STORE_SUPPLIER_INVOICE_PATH, Consts.STORE_SUPPLIER_INVOICE_CATEGORY);
        entityManager.merge(accessRight41);
        AccessRight accessRight42 = new AccessRight();
        accessRight42.create(Consts.VIEW_SUPPLIER_INVOICE, Consts.VIEW_SUPPLIER_INVOICE_PATH, Consts.VIEW_SUPPLIER_INVOICE_CATEGORY);
        entityManager.merge(accessRight42);
        AccessRight accessRight43 = new AccessRight();
        accessRight43.create(Consts.CREATE_SUPPLIER_PAYMENT_RECORD, Consts.CREATE_SUPPLIER_PAYMENT_RECORD_PATH, Consts.CREATE_SUPPLIER_PAYMENT_RECORD_CATEGORY);
        entityManager.merge(accessRight43);
        AccessRight accessRight44 = new AccessRight();
        accessRight44.create(Consts.VIEW_SUPPLIER_PAYMENT_RECORD, Consts.VIEW_SUPPLIER_PAYMENT_RECORD_PATH, Consts.VIEW_SUPPLIER_PAYMENT_RECORD_CATEGORY);
        entityManager.merge(accessRight44);
        AccessRight accessRight45 = new AccessRight();
        accessRight45.create(Consts.STORE_SUPPLIER_RECEIPT, Consts.STORE_SUPPLIER_RECEIPT_PATH, Consts.STORE_SUPPLIER_RECEIPT_CATEGORY);
        entityManager.merge(accessRight45);
        AccessRight accessRight46 = new AccessRight();
        accessRight46.create(Consts.VIEW_SUPPLIER_RECEIPT, Consts.VIEW_SUPPLIER_RECEIPT_PATH, Consts.VIEW_SUPPLIER_RECEIPT_CATEGORY);
        entityManager.merge(accessRight46);
        AccessRight accessRight49 = new AccessRight();
        accessRight49.create(Consts.VIEW_FINANCIAL_DASHBOARD, Consts.VIEW_FINANCIAL_DASHBOARD_PATH, Consts.VIEW_FINANCIAL_DASHBOARD_CATEGORY);
        entityManager.merge(accessRight49);
        AccessRight accessRight50 = new AccessRight();
        accessRight50.create(Consts.VIEW_PRODUCT_INVENTORY, Consts.VIEW_PRODUCT_INVENTORY_PATH, Consts.VIEW_PRODUCT_INVENTORY_CATEGORY);
        entityManager.merge(accessRight50);
        AccessRight accessRight60 = new AccessRight();
        accessRight60.create(Consts.VIEW_RAW_MATERIAL_INVENTORY, Consts.VIEW_RAW_MATERIAL_INVENTORY_PATH, Consts.VIEW_RAW_MATERIAL_INVENTORY_CATEGORY);
        entityManager.merge(accessRight60);
        AccessRight accessRight61 = new AccessRight();
        accessRight61.create(Consts.VIEW_ORDER_LIST, Consts.VIEW_ORDER_LIST_PATH, Consts.VIEW_ORDER_LIST_CATEGORY);
        entityManager.merge(accessRight61);
        AccessRight accessRight62 = new AccessRight();
        accessRight62.create(Consts.CREATE_RM_PURCHASE_ORDER, Consts.CREATE_RM_PURCHASE_ORDER_PATH, Consts.CREATE_RM_PURCHASE_ORDER_CATEGORY);
        entityManager.merge(accessRight62);
        AccessRight accessRight63 = new AccessRight();
        accessRight63.create(Consts.VIEW_RM_PURCHASE_ORDER, Consts.VIEW_RM_PURCHASE_ORDER_PATH, Consts.VIEW_RM_PURCHASE_ORDER_CATEGORY);
        entityManager.merge(accessRight63);
        AccessRight accessRight64 = new AccessRight();
        accessRight64.create(Consts.STORE_RM_SALES_ORDER, Consts.STORE_RM_SALES_ORDER_PATH, Consts.STORE_RM_SALES_ORDER_CATEGORY);
        entityManager.merge(accessRight64);
        AccessRight accessRight65 = new AccessRight();
        accessRight65.create(Consts.VIEW_RM_SALES_ORDER, Consts.VIEW_RM_SALES_ORDER_PATH, Consts.VIEW_RM_SALES_ORDER_CATEGORY);
        entityManager.merge(accessRight65);
        AccessRight accessRight66 = new AccessRight();
        accessRight66.create(Consts.ADD_NEW_SUPPLIER, Consts.ADD_NEW_SUPPLIER_PATH, Consts.ADD_NEW_SUPPLIER_CATEGORY);
        entityManager.merge(accessRight66);
        AccessRight accessRight67 = new AccessRight();
        accessRight67.create(Consts.VIEW_SUPPLIER_LIST, Consts.VIEW_SUPPLIER_LIST_PATH, Consts.VIEW_SUPPLIER_LIST_CATEGORY);
        entityManager.merge(accessRight67);
        AccessRight accessRight68 = new AccessRight();
        accessRight68.create(Consts.RATE_SUPPLIER, Consts.RATE_SUPPLIER_PATH, Consts.RATE_SUPPLIER_CATEGORY);
        entityManager.merge(accessRight68);
        AccessRight accessRight69 = new AccessRight();
        accessRight69.create(Consts.CREATE_GOODS_RECEIPT, Consts.CREATE_GOODS_RECEIPT_PATH, Consts.CREATE_GOODS_RECEIPT_CATEGORY);
        entityManager.merge(accessRight69);
        AccessRight accessRight81 = new AccessRight();
        accessRight81.create(Consts.VIEW_SUPPLIER_RATING, Consts.VIEW_SUPPLIER_RATING_PATH, Consts.VIEW_SUPPLIER_RATING_CATEGORY);
        entityManager.merge(accessRight81);
        AccessRight accessRight82 = new AccessRight();
        accessRight82.create(Consts.CREATE_PURCHASE_PLAN, Consts.CREATE_PURCHASE_PLAN_PATH, Consts.CREATE_PURCHASE_PLAN_CATEGORY);
        entityManager.merge(accessRight82);
        AccessRight accessRight83 = new AccessRight();
        accessRight83.create(Consts.VIEW_PURCHASE_PLAN, Consts.VIEW_PURCHASE_PLAN_PATH, Consts.VIEW_PURCHASE_PLAN_CATEGORY);
        entityManager.merge(accessRight83);
    }

    private void createSecurityRoles() {
        Query query = entityManager.createQuery("SELECT ar FROM AccessRight ar");
        List<AccessRight> ars = (List<AccessRight>) query.getResultList();

        SecurityRole techStaff = new SecurityRole();
        techStaff.create(Consts.TECH_STAFF_ROLE, Consts.TECH_DEP);
        SecurityRole salesExecutive = new SecurityRole();
        salesExecutive.create(Consts.SALES_EXECUTIVE_ROLE, Consts.SALES_DEP);
        SecurityRole salesManager = new SecurityRole();
        salesManager.create(Consts.SALES_MANAGER_ROLE, Consts.SALES_DEP);
        SecurityRole salesVP = new SecurityRole();
        salesVP.create(Consts.SALES_VP_ROLE, Consts.SALES_DEP);
        SecurityRole mrpVP = new SecurityRole();
        mrpVP.create(Consts.MRP_VP_ROLE, Consts.MRP_DEP);
        SecurityRole mrpManager = new SecurityRole();
        mrpManager.create(Consts.MRP_MANAGER_ROLE, Consts.MRP_DEP);
        SecurityRole finStaff = new SecurityRole();
        finStaff.create(Consts.FIN_STAFF_ROLE, Consts.FIN_DEP);
        SecurityRole finVP = new SecurityRole();
        finVP.create(Consts.FIN_VP_ROLE, Consts.FIN_DEP);
        SecurityRole scmVP = new SecurityRole();
        scmVP.create(Consts.SUPPLY_CHAIN_VP_ROLE, Consts.SUPPLY_CHAIN_DEP);

        for (AccessRight ar : ars) {
            if (ar.getMethodName().equals(Consts.CREATE_ROLE)) {
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.DELETE_ROLE)) {
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.EDIT_ROLE)) {
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_ROLE)) {
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SYSTEM_USER_ACCOUNT)) {
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.MANAGE_SYSTEM_USER_ACCOUNT)) {
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.ANNOUCEMENT_CREATE)) {
                salesVP.getAccessRights().add(ar);
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.ANNOUCEMENT_MANAGE)) {
                salesVP.getAccessRights().add(ar);
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.LOGGING_LOGS_VIEW)) {
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_JOB_LIST_ONE_DEP)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
                techStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_ALL_SALESLEAD)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SALESLEAD)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_ALL_CUSTOMER)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_CUSTOMER)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SALES_INQUIRY)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SALES_INQUIRY)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SALES_QUOTATION)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SALES_QUOTATION)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_PURCHASE_ORDER)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_PURCHASE_ORDER)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SALES_ORDER)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.MANAGE_SALES_PRICE)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_ANALYTICS_CLIENT)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SALES_ORDER)) {
                salesExecutive.getAccessRights().add(ar);
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SALES_FIGURE)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_DOCUMENT_FLOW)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
                salesExecutive.getAccessRights().add(ar);
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_ORDER_DISCOUNT_GROUP)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_MEMBER_DISCOUNT_GROUP)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.MANAGE_MEMBER_DISCOUNT_GROUP)) {
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.MANAGE_ORDER_DISCOUNT_GROUP)) {
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_JOB_LIST_ONE_DEP)) {
                salesManager.getAccessRights().add(ar);
                salesVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SALES_FORECAST)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.MANAGE_BASE_PRICE)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SALES_FORECAST)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.MANAGE_FINISHED_GOODS)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.EDIT_SALES_FORECAST)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_MRP_SOP)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_MRP_SOP)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.EDIT_MRP_SOP)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } //            else if (ar.getMethodName().equals(Consts.CREATE_DAILY_MPS)) {
            //                mrpManager.getAccessRights().add(ar);
            //                mrpVP.getAccessRights().add(ar);
            //            } 
            else if (ar.getMethodName().equals(Consts.VIEW_DAILY_MPS)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.EDIT_DAILY_MPS)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_WEEKLY_MPS)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_MRP_MRP)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_MRP_MRP)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.EDIT_MRP_MRP)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.SIMULATE_FOR_RFQ)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.SIMULATE_FOR_SO)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_BACKORDER)) {
                mrpManager.getAccessRights().add(ar);
                mrpVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_CREDIT_GROUP)) {
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_CREDIT_GROUP)) {
                finStaff.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.MANAGE_CREDIT_GROUP)) {
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_CREDIT_ACCOUNT)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_CREDIT_ACCOUNT)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SALES_INVOICE)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SALES_INVOICE)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_CUSTOMER_PAYMENT_RECORD)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_CUSTOMER_PAYMENT_RECORD)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_RECEIPT)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.STORE_SUPPLIER_INVOICE)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SUPPLIER_INVOICE)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_SUPPLIER_PAYMENT_RECORD)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SUPPLIER_PAYMENT_RECORD)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.STORE_SUPPLIER_RECEIPT)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SUPPLIER_RECEIPT)) {
                finStaff.getAccessRights().add(ar);
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_FINANCIAL_DASHBOARD)) {
                finVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_PRODUCT_INVENTORY)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_RAW_MATERIAL_INVENTORY)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_ORDER_LIST)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_RM_PURCHASE_ORDER)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_RM_PURCHASE_ORDER)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.STORE_RM_SALES_ORDER)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_RM_SALES_ORDER)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.ADD_NEW_SUPPLIER)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SUPPLIER_LIST)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.RATE_SUPPLIER)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_GOODS_RECEIPT)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_SUPPLIER_RATING)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.CREATE_PURCHASE_PLAN)) {
                scmVP.getAccessRights().add(ar);
            } else if (ar.getMethodName().equals(Consts.VIEW_PURCHASE_PLAN)) {
                scmVP.getAccessRights().add(ar);
            }
        }

        entityManager.merge(finStaff);
        entityManager.merge(finVP);
        entityManager.merge(techStaff);
        entityManager.merge(salesExecutive);
        entityManager.merge(salesVP);
        entityManager.merge(salesManager);
        entityManager.merge(mrpManager);
        entityManager.merge(mrpVP);
        entityManager.merge(scmVP);
    }

    private void createSuperAdmin() {
        Staff superAdmin = new Staff();
        superAdmin.create("Super", "Admin", Consts.ADMIN_DEP);
        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr");
        // security role
        superAdmin.getSecurityRoles().addAll(query.getResultList());
        // system user account
        superAdmin.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "winterbells815@gmail.com", "admin", "super",
                Timestamp.valueOf("2011-08-29 13:30:00"), "What is your favorite color?", "red");
        entityManager.merge(superAdmin);
    }

    private void createTechnicalStaff() {
        Staff techStaff = new Staff();
        techStaff.create("Ying", "Zhang", Consts.TECH_DEP);
        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query.setParameter("p1", Consts.TECH_STAFF_ROLE);
        SecurityRole sr = (SecurityRole) query.getSingleResult();
        // security role
        techStaff.getSecurityRoles().add(sr);
        // system user account
        techStaff.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "z-ying@comp.nus.edu.sg", "111111", "zhangying",
                Timestamp.valueOf("2011-08-29 13:30:00"), "What is your favorite color?", "red");

        entityManager.merge(techStaff);
    }

    private void createSalesExecutives() {
        Staff salesExecutive1 = new Staff();
        Staff salesExecutive2 = new Staff();
        Staff salesExecutive3 = new Staff();

        salesExecutive1.create("Jack", "Cheng", Consts.SALES_DEP);
        salesExecutive2.create("Kenneth", "Lim", Consts.SALES_DEP);
        salesExecutive3.create("Pearl", "Chuan", Consts.SALES_DEP);

        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query.setParameter("p1", Consts.SALES_EXECUTIVE_ROLE);
        SecurityRole sr = (SecurityRole) query.getSingleResult();

        salesExecutive1.getSecurityRoles().add(sr);
        salesExecutive1.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "is3102m01.01@gmail.com", "adminadmin", "jackcheng",
                Timestamp.valueOf("2011-01-01 00:05:00"), "What is your favorite color?", "red");
        salesExecutive2.getSecurityRoles().add(sr);
        salesExecutive2.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "kennlim87@gmail.com", "adminadmin", "zhiqi",
                Timestamp.valueOf("2011-01-02 00:05:00"), "What is your favorite color?", "red");
        salesExecutive3.getSecurityRoles().add(sr);
        salesExecutive3.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "is3102m01.02@gmail.com", "adminadmin", "pearlchuan",
                Timestamp.valueOf("2011-01-01 00:15:00"), "What is your favorite color?", "red");

        entityManager.merge(salesExecutive1);
        entityManager.merge(salesExecutive2);
        entityManager.merge(salesExecutive3);
    }

    private void createSalesManagers() {
        Staff salesManager = new Staff();

        salesManager.create("Lucy", "Yuan", Consts.SALES_DEP);

        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query.setParameter("p1", Consts.SALES_MANAGER_ROLE);
        SecurityRole sr = (SecurityRole) query.getSingleResult();

        salesManager.getSecurityRoles().add(sr);
        salesManager.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "zhiqi@comp.nus.edu.sg", "adminadmin", "lucyyuan",
                Timestamp.valueOf("2011-01-04 00:12:05"), "What is your favorite color?", "red");
        entityManager.merge(salesManager);
    }

    private void createSalesVPs() {
        Staff salesVP = new Staff();

        salesVP.create("Yuwei", "Jin", Consts.SALES_DEP);

        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query.setParameter("p1", Consts.SALES_VP_ROLE);
        SecurityRole sr = (SecurityRole) query.getSingleResult();

        salesVP.getSecurityRoles().add(sr);
        salesVP.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "chenzhiqi2002@hotmail.com", "adminadmin", "yuwei",
                Timestamp.valueOf("2011-01-04 00:12:05"), "What is your favorite color?", "red");
        entityManager.merge(salesVP);
    }

    private void createMRPStaff() {
        Staff mrpStaff = new Staff();
        mrpStaff.create("Xin", "Zhu", Consts.MRP_DEP);
        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query.setParameter("p1", Consts.MRP_VP_ROLE);
        SecurityRole sr = (SecurityRole) query.getSingleResult();
        // security role
        mrpStaff.getSecurityRoles().add(sr);
        // system user account
        mrpStaff.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "zhangying900815@gmail.com", "111111", "zhuxin",
                Timestamp.valueOf("2011-08-29 13:30:00"), "What is your favorite color?", "red");

        entityManager.merge(mrpStaff);
    }

    private void createFinanceStaff() {
        Staff financeStaff = new Staff();

        financeStaff.create("Kenneth", "Lim", Consts.FIN_DEP);

        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query.setParameter("p1", Consts.FIN_VP_ROLE);
        SecurityRole sr = (SecurityRole) query.getSingleResult();

        financeStaff.getSecurityRoles().add(sr);
        financeStaff.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "jinyw990@gmail.com", "admin", "kenn",
                Timestamp.valueOf("2011-01-04 00:12:05"), "What is your favorite color?", "red");
        entityManager.merge(financeStaff);

        Staff financeStaff2 = new Staff();

        financeStaff2.create("Ken", "Sun", Consts.FIN_DEP);

        Query query2 = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query2.setParameter("p1", Consts.FIN_STAFF_ROLE);
        sr = (SecurityRole) query2.getSingleResult();

        financeStaff2.getSecurityRoles().add(sr);
        financeStaff2.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "zhuxin1012@gmail.com", "admin", "kenny",
                Timestamp.valueOf("2011-01-04 00:12:05"), "What is your favorite color?", "red");
        entityManager.merge(financeStaff2);
    }

    private void createSupplyChainStaff() {

        Staff scmVP = new Staff();
        scmVP.create("Zhou", "Hong", Consts.SUPPLY_CHAIN_DEP);
        Query query = entityManager.createQuery("SELECT sr FROM SecurityRole sr WHERE sr.roleName=:p1");
        query.setParameter("p1", Consts.SUPPLY_CHAIN_VP_ROLE);
        SecurityRole sr = (SecurityRole) query.getSingleResult();
        scmVP.getSecurityRoles().add(sr);
        scmVP.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "misseva1989@gmail.com", "admin", "zhouhong",
                Timestamp.valueOf("2011-01-04 00:12:05"), "What is your favorite color?", "red");
        entityManager.merge(scmVP);
    }

    private void createProducts() {
        for (int i = 0; i < 4; i++) {
            Product newProduct = new Product(i);
            switch (i) {
                case 0:
                    newProduct.setDescription("Red boxes");
                    break;
                case 1:
                    newProduct.setDescription("Blue boxes");
                    break;
                case 2:
                    newProduct.setDescription("Green boxes");
                    break;
                case 3:
                    newProduct.setDescription("Yellow boxes");
                    break;
                default:
                    break;
            }
            entityManager.merge(newProduct);
        }
    }

    private void createSalesLead() {
        SalesLead sl1 = new SalesLead();
        SalesLead sl2 = new SalesLead();
        SalesLead sl3 = new SalesLead();
        SalesLead sl4 = new SalesLead();
        SalesLead sl5 = new SalesLead();
        SalesLead sl6 = new SalesLead();

        ContactRecord cr1 = new ContactRecord();
        cr1.setName("John");
        cr1.setJobTitle("Manager");
        cr1.setEmail("john@supermarket.com");
        cr1.setPhone("91234567");

        ContactRecord cr2 = new ContactRecord();
        cr2.setName("Anderson");
        cr2.setJobTitle("Director");
        cr2.setEmail("Andy@supermarket.com");
        cr2.setPhone("91234567");

        ContactRecord cr3 = new ContactRecord();
        cr3.setName("Alvin");
        cr3.setJobTitle("Executive");
        cr3.setEmail("alvin@finedinning.com");
        cr3.setPhone("91234533");

        ContactRecord cr4 = new ContactRecord();
        cr4.setName("Serna Wu");
        cr4.setJobTitle("Manager");
        cr4.setEmail("sernawu@capitalhotel.com");
        cr4.setPhone("38492019");

        ContactRecord cr5 = new ContactRecord();
        cr5.setName("Calvin Tan");
        cr5.setJobTitle("Executive");
        cr5.setEmail("calvintan@lunarbar.com");
        cr5.setPhone("99492019");

        ContactRecord cr6 = new ContactRecord();
        cr6.setName("Hongyi Goh");
        cr6.setJobTitle("Manager");
        cr6.setEmail("hongyigoh@lunarbar.com");
        cr6.setPhone("99492337");

        ContactRecord cr7 = new ContactRecord();
        cr7.setName("Fec Lee");
        cr7.setJobTitle("Director");
        cr7.setEmail("feclee@creative.com");
        cr7.setPhone("99456337");

        ContactRecord cr8 = new ContactRecord();
        cr8.setName("Yang Xue");
        cr8.setJobTitle("Director");
        cr8.setEmail("yangxue@smu.edu.sg");
        cr8.setPhone("123499456337");

        Collection crs1 = new ArrayList<ContactRecord>();
        crs1.add(cr1);
        crs1.add(cr2);

        Collection crs2 = new ArrayList<ContactRecord>();
        crs2.add(cr3);

        Collection crs3 = new ArrayList<ContactRecord>();
        crs3.add(cr4);

        Collection crs4 = new ArrayList<ContactRecord>();
        crs4.add(cr5);
        crs4.add(cr6);

        Collection crs5 = new ArrayList<ContactRecord>();
        crs5.add(cr7);

        Collection crs6 = new ArrayList<ContactRecord>();
        crs6.add(cr8);

        Query query1 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query1.setParameter("p1", "jackcheng");
        Staff ce1 = (Staff) query1.getSingleResult();

        Query query2 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query2.setParameter("p1", "zhiqi");
        Staff ce2 = (Staff) query2.getSingleResult();

        sl1.create("20110111001", "Health First", "DirectSale", crs1, ce1, "Gym");
        sl2.create("20110216001", "Fine Dinning", "WholeSale", crs2, ce2, "Dining Restaurant");
        sl3.create("20110316002", "Capital Hotel", "DirectSale", crs3, ce1, "Hotel");
        sl4.create("20110417001", "Lunar Bar", "DirectSale", crs4, ce2, "Dining Restaurant");
        sl5.create("20110517002", "Creative", "WholeSale", crs5, ce2, "Corporates");
        sl6.create("20110617003", "SMU Finance Department", "DirectSale", crs6, ce1, "Education Institution");

        //Billing Address
//        Address billing = new Address();
//        billing.setAddressType("Billing");
//        billing.setAddressLine1("NUS School of Computing");
//        billing.setAddressLine2("1 College Road");
//        billing.setStateName("Singapore");
//        billing.setCity("Singapore");
//        billing.setCountry("Singapore");
//        billing.setZipCode("123456");
//        //sl1.setBillingAddress(billing);

        //Shipping Address 1
        Address shipping = new Address();
        shipping.setAddressType("Shipping");
        shipping.setAddressLine1("NUS School of Computing");
        shipping.setAddressLine2("2 College Road");
        shipping.setStateName("Singapore");
        shipping.setCity("Singapore");
        shipping.setCountry("Singapore");
        shipping.setZipCode("123456");

        //Shipping Address 2
        Address shipping2 = new Address();
        shipping2.setAddressType("Shipping");
        shipping2.setAddressLine1("Snack Barz Shop");
        shipping2.setAddressLine2("3 Woodsville Street");
        shipping2.setStateName("California");
        shipping2.setCity("San Francisco");
        shipping2.setCountry("United Sates");
        shipping2.setZipCode("12345");

        //Shipping Address 3
        Address shipping3 = new Address();
        shipping3.setAddressType("Shipping");
        shipping3.setAddressLine1("Snack Barz Shop");
        shipping3.setAddressLine2("3 Woodsville Street");
        shipping3.setStateName("California");
        shipping3.setCity("San Francisco");
        shipping3.setCountry("United Sates");
        shipping3.setZipCode("12345");

        //Shipping Address 4
        Address shipping4 = new Address();
        shipping4.setAddressType("Shipping");
        shipping4.setAddressLine1("Snack Barz Shop");
        shipping4.setAddressLine2("3 Woodsville Street");
        shipping4.setStateName("California");
        shipping4.setCity("San Francisco");
        shipping4.setCountry("United Sates");
        shipping4.setZipCode("12345");

        //Shipping Address 5
        Address shipping5 = new Address();
        shipping5.setAddressType("Shipping");
        shipping5.setAddressLine1("Snack Barz Shop");
        shipping5.setAddressLine2("3 Woodsville Street");
        shipping5.setStateName("California");
        shipping5.setCity("San Francisco");
        shipping5.setCountry("United Sates");
        shipping5.setZipCode("12345");

        //Shipping Address 6
        Address shipping6 = new Address();
        shipping6.setAddressType("Shipping");
        shipping6.setAddressLine1("Snack Barz Shop");
        shipping6.setAddressLine2("3 Woodsville Street");
        shipping6.setStateName("California");
        shipping6.setCity("San Francisco");
        shipping6.setCountry("United Sates");
        shipping6.setZipCode("12345");

        //Shipping Address 7
        Address shipping7 = new Address();
        shipping7.setAddressType("Shipping");
        shipping7.setAddressLine1("Snack Barz Shop");
        shipping7.setAddressLine2("3 Woodsville Street");
        shipping7.setStateName("California");
        shipping7.setCity("San Francisco");
        shipping7.setCountry("United Sates");
        shipping7.setZipCode("12345");

        //Shipping Address 8
        Address shipping8 = new Address();
        shipping8.setAddressType("Shipping");
        shipping8.setAddressLine1("Snack Barz Shop");
        shipping8.setAddressLine2("3 Woodsville Street");
        shipping8.setStateName("California");
        shipping8.setCity("San Francisco");
        shipping8.setCountry("United Sates");
        shipping8.setZipCode("12345");

        //Shipping Address 9
        Address shipping9 = new Address();
        shipping9.setAddressType("Shipping");
        shipping9.setAddressLine1("Snack Barz Shop");
        shipping9.setAddressLine2("3 Woodsville Street");
        shipping9.setStateName("California");
        shipping9.setCity("San Francisco");
        shipping9.setCountry("United Sates");
        shipping9.setZipCode("12345");


        sl1.getShippingAddress().add(shipping);
        sl2.getShippingAddress().add(shipping2);
        sl2.getShippingAddress().add(shipping3);
        sl3.getShippingAddress().add(shipping4);
        sl4.getShippingAddress().add(shipping5);
        sl4.getShippingAddress().add(shipping6);
        sl5.getShippingAddress().add(shipping7);
        sl6.getShippingAddress().add(shipping8);
        sl6.getShippingAddress().add(shipping9);

        entityManager.merge(sl1);
        entityManager.merge(sl2);
        entityManager.merge(sl3);
        entityManager.merge(sl4);
        entityManager.merge(sl5);
        entityManager.merge(sl6);
    }

    private void createCustomer1() {
        Customer c1 = new Customer();

        ContactRecord cr1 = new ContactRecord();
        cr1.setName("Novita");
        cr1.setJobTitle("Manager");
        cr1.setEmail("is3102m01demo@gmail.com");
        cr1.setPhone("91234567");

        ContactRecord cr2 = new ContactRecord();
        cr2.setName("Mike");
        cr2.setJobTitle("Director");
        cr2.setEmail("kennlim87@gmail.com");

        cr2.setPhone("91234567");

        Collection crs = new ArrayList<ContactRecord>();
        crs.add(cr1);
        crs.add(cr2);

        c1.setClientId("20110113001");
        c1.setCompanyName("Singapore Fitness");
        c1.setCategory("WholeSale");
        c1.setContactRecords(crs);
        c1.setIndustry("Supermarket");

        Query query2 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query2.setParameter("p1", "pearlchuan");
        Staff ce3 = (Staff) query2.getSingleResult();
        c1.setCustomerExecutive(ce3);

        Query query3 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query3.setParameter("p1", "kenn");
        Staff ce4 = (Staff) query3.getSingleResult();
        c1.setFinanceStaff(ce4);

        //MemberDiscountGroup
        c1.setMemberDiscountGroup(mdgs.get(2));
        c1.setAccumulatedPurchases((double) 85000);
        mdgs.get(2).getCustomers().add(c1);

        //Credit Account
        CreditGroup cg = (CreditGroup) entityManager.createQuery("SELECT g FROM CreditGroup g").getResultList().get(0);
        CreditAccount ca = new CreditAccount();
        ca.setCustomer(c1);
        ca.setCreditGroup(cg);
        ca.setCreditUsed(28990);
        ca.setIsDefault(false);
        cg.getCreditAccounts().add(ca);
        c1.setCreditAccount(ca);

        //Billing Address
        Address billing = new Address();
        billing.setAddressType("Billing");
        billing.setAddressLine1("198 Science Park 2");
        billing.setAddressLine2("Level 2 Room 606");
        billing.setZipCode("84423");
        billing.setCity("Singapore");
        billing.setCountry("Singapore");
        billing.setStateName("Singapore");
        c1.setBillingAddress(billing);

        //Shipping Address
        Address shipping = new Address();
        shipping.setAddressType("Shipping");
        shipping.setAddressLine1("Engine Park 2");
        shipping.setAddressLine2("Level 2 Room 606");
        shipping.setZipCode("84423");
        shipping.setCity("Singapore");
        shipping.setCountry("Singapore");
        shipping.setStateName("Singapore");
        c1.getShippingAddress().add(shipping);

        Address shipping2 = new Address();
        shipping2.setAddressType("Shipping");
        shipping2.setAddressLine1("North West 199");
        shipping2.setAddressLine2("Level 15, Section 2");
        shipping2.setZipCode("88223");
        shipping2.setCity("Singapore");
        shipping2.setCountry("Singapore");
        shipping2.setStateName("Singapore");
        c1.getShippingAddress().add(shipping2);

        entityManager.merge(c1);
    }

    private void createCustomer2() {
        Customer c1 = new Customer();

        ContactRecord cr1 = new ContactRecord();
        cr1.setName("Stephane Weir");
        cr1.setJobTitle("Manager");
        cr1.setEmail("is3102m01demo@gmail.com");
        cr1.setPhone("91233367");

        Collection crs = new ArrayList<SalesLead>();
        crs.add(cr1);

        c1.setClientId("20110218001");
        c1.setCompanyName("Pop Star");
        c1.setCategory("WholeSale");
        c1.setContactRecords(crs);
        c1.setIndustry("Corporate");

        Query query2 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query2.setParameter("p1", "pearlchuan");
        Staff ce3 = (Staff) query2.getSingleResult();
        c1.setCustomerExecutive(ce3);

        Query query3 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query3.setParameter("p1", "kenn");
        Staff ce4 = (Staff) query3.getSingleResult();
        c1.setFinanceStaff(ce4);

        //MemberDiscountGroup
        c1.setMemberDiscountGroup(mdgs.get(1));
        c1.setAccumulatedPurchases((double) 50000);
        mdgs.get(1).getCustomers().add(c1);
        //Credit Account
        CreditGroup cg = (CreditGroup) entityManager.createQuery("SELECT g FROM CreditGroup g").getResultList().get(2);
        CreditAccount ca = new CreditAccount();
        ca.setCreditGroup(cg);
        ca.setCustomer(c1);
        ca.setCreditUsed(15000);
        ca.setIsDefault(false);
        cg.getCreditAccounts().add(ca);
        c1.setCreditAccount(ca);


        //Billing Address
        Address billing = new Address();
        billing.setAddressType("Billing");
        billing.setAddressLine1("24 Kent Ridge Road");
        billing.setAddressLine2("Level 2 Section 210");
        billing.setZipCode("33423");
        billing.setStateName("Singapore");
        billing.setCity("Singapore");
        billing.setCountry("Singapore");
        c1.setBillingAddress(billing);

        //Shipping Address
        Address shipping = new Address();
        shipping.setAddressType("Shipping");
        shipping.setAddressLine1("24 Kent Ridge Road");
        shipping.setAddressLine2("Level 2 Section 210");
        shipping.setZipCode("33423");
        shipping.setStateName("Singapore");
        shipping.setCity("Singapore");
        shipping.setCountry("Singapore");
        c1.getShippingAddress().add(shipping);


        entityManager.merge(c1);
    }

    private void createCustomer3() {
        Customer c1 = new Customer();

        ContactRecord cr1 = new ContactRecord();
        cr1.setName("Dennis Tan");
        cr1.setJobTitle("Executive");
        cr1.setEmail("is3102m01demo@gmail.com");
        cr1.setPhone("91233327");

        Collection crs = new ArrayList<SalesLead>();
        crs.add(cr1);

        c1.setClientId("20110320002");
        c1.setCompanyName("First Hospital");
        c1.setCategory("DirectSale");
        c1.setContactRecords(crs);
        c1.setIndustry("Hospital");

        Query query2 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query2.setParameter("p1", "pearlchuan");
        Staff ce3 = (Staff) query2.getSingleResult();
        c1.setCustomerExecutive(ce3);

        Query query3 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query3.setParameter("p1", "kenn");
        Staff ce4 = (Staff) query3.getSingleResult();
        c1.setFinanceStaff(ce4);

        //MemberDiscountGroup
        c1.setMemberDiscountGroup(mdgs.get(0));
        mdgs.get(0).getCustomers().add(c1);
        c1.setAccumulatedPurchases((double) 5000);

        //Credit Account
        CreditGroup cg = (CreditGroup) entityManager.createQuery("SELECT g FROM CreditGroup g").getResultList().get(3);
        CreditAccount ca = new CreditAccount();
        ca.setCreditGroup(cg);
        ca.setCustomer(c1);
        ca.setCreditUsed(0);
        ca.setIsDefault(false);
        ca.setCreditBalance(cg.getCreditLimitForDs());
        cg.getCreditAccounts().add(ca);
        c1.setCreditAccount(ca);

        //Billing Address
        Address billing = new Address();
        billing.setAddressType("Billing");
        billing.setAddressLine1("31st Morrison Road");
        billing.setZipCode("12423");
        billing.setCity("Sydney");
        billing.setStateName("New South Wales");
        billing.setCountry("Australia");
        c1.setBillingAddress(billing);

        //Shipping Address
        Address shipping = new Address();
        shipping.setAddressType("Shipping");
        shipping.setAddressLine1("31st Morrison Road");
        shipping.setZipCode("12423");
        shipping.setCity("Sydney");
        shipping.setStateName("New South Wales");
        shipping.setCountry("Australia");
        c1.getShippingAddress().add(shipping);

        entityManager.merge(c1);
    }

    private void createCustomer4() {
        Customer c1 = new Customer();

        ContactRecord cr1 = new ContactRecord();
        cr1.setName("Mandy");
        cr1.setJobTitle("Manager");
        cr1.setEmail("is3102m01demo@gmail.com");
        cr1.setPhone("91233267");

        Collection crs = new ArrayList<SalesLead>();
        crs.add(cr1);

        c1.setClientId("20110419001");
        c1.setCompanyName("Roses Park");
        c1.setCategory("DirectSale");
        c1.setContactRecords(crs);
        c1.setIndustry("Corporate");

        Query query2 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query2.setParameter("p1", "pearlchuan");
        Staff ce3 = (Staff) query2.getSingleResult();
        c1.setCustomerExecutive(ce3);

        Query query3 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query3.setParameter("p1", "kenn");
        Staff ce4 = (Staff) query3.getSingleResult();
        c1.setFinanceStaff(ce4);

        //MemberDiscountGroup
        c1.setMemberDiscountGroup(mdgs.get(2));
        c1.setAccumulatedPurchases((double) 30000);
        mdgs.get(2).getCustomers().add(c1);

        //Credit Account

        CreditGroup cg = (CreditGroup) entityManager.createQuery("SELECT g FROM CreditGroup g").getResultList().get(2);
        CreditAccount ca = new CreditAccount();
        ca.setCreditGroup(cg);
        ca.setCustomer(c1);
        ca.setCreditUsed(15000);
        ca.setIsDefault(false);
        cg.getCreditAccounts().add(ca);
        c1.setCreditAccount(ca);

        //Billing Address
        Address billing = new Address();
        billing.setAddressType("Billing");
        billing.setAddressLine1("No. 2 Orchard Road");
        billing.setZipCode("123356");
        billing.setCity("Singapore");
        billing.setStateName("Singapore");
        billing.setCountry("Singapore");
        c1.setBillingAddress(billing);

        //Shipping Address
        Address shipping = new Address();
        shipping.setAddressType("Shipping");
        shipping.setAddressLine1("No. 2 Orchard Road");
        shipping.setZipCode("123356");
        shipping.setCity("Singapore");
        shipping.setStateName("Singapore");
        shipping.setCountry("Singapore");
        c1.getShippingAddress().add(shipping);

        entityManager.merge(c1);

    }

    private void createCustomer5() {
        Customer c1 = new Customer();

        ContactRecord cr1 = new ContactRecord();
        cr1.setName("Evagni Alexi");
        cr1.setJobTitle("Executive");
        cr1.setEmail("is3102m01demo@gmail.com");
        cr1.setPhone("33891233327");

        Collection crs = new ArrayList<SalesLead>();
        crs.add(cr1);

        c1.setClientId("20110522001");
        c1.setCompanyName("World Fitness");
        c1.setCategory("DirectSale");
        c1.setContactRecords(crs);
        c1.setIndustry("Gym");

        Query query2 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query2.setParameter("p1", "pearlchuan");
        Staff ce3 = (Staff) query2.getSingleResult();
        c1.setCustomerExecutive(ce3);

        Query query3 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query3.setParameter("p1", "kenn");
        Staff ce4 = (Staff) query3.getSingleResult();
        c1.setFinanceStaff(ce4);

        //MemberDiscountGroup
        c1.setMemberDiscountGroup(mdgs.get(0));
        c1.setAccumulatedPurchases((double) 9000);
        mdgs.get(0).getCustomers().add(c1);

        //Credit Account
        CreditGroup cg = (CreditGroup) entityManager.createQuery("SELECT g FROM CreditGroup g").getResultList().get(0);
        CreditAccount ca = new CreditAccount();
        ca.setCreditGroup(cg);
        ca.setCustomer(c1);
        ca.setCreditUsed(0);
        ca.setIsDefault(false);
        cg.getCreditAccounts().add(ca);
        c1.setCreditAccount(ca);

        //Billing Address
        Address billing = new Address();
        billing.setAddressType("Billing");
        billing.setAddressLine1("198 Saint Petersburg Road");
        billing.setAddressLine2("No. 39, Section99");
        billing.setZipCode("82423");
        billing.setCity("Saint Petersburg");
        billing.setStateName("Leningrad Region");
        billing.setCountry("Russia");
        c1.setBillingAddress(billing);

        //Shipping Address
        Address shipping = new Address();
        shipping.setAddressType("Shipping");
        shipping.setAddressLine1("198 Saint Petersburg Road");
        shipping.setAddressLine2("No. 39, Section99");
        shipping.setZipCode("82423");
        shipping.setCity("Saint Petersburg");
        shipping.setStateName("Leningrad Region");
        shipping.setCountry("Russia");
        c1.getShippingAddress().add(shipping);
        entityManager.merge(c1);

    }

    private void createCustomer6() {
        Customer c1 = new Customer();

        ContactRecord cr1 = new ContactRecord();
        cr1.setName("Stephane John");
        cr1.setJobTitle("Manager");
        cr1.setEmail("is3102m01demo@gmail.com");
        cr1.setPhone("91201367");

        Collection crs = new ArrayList<SalesLead>();
        crs.add(cr1);

        c1.setClientId("20110702001");
        c1.setCompanyName("Public Food");
        c1.setCategory("WholeSale");
        c1.setContactRecords(crs);
        c1.setIndustry("Fast Food Restaurant");

        Query query2 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query2.setParameter("p1", "pearlchuan");
        Staff ce3 = (Staff) query2.getSingleResult();
        c1.setCustomerExecutive(ce3);

        Query query3 = entityManager.createQuery(("SELECT s FROM Staff s WHERE s.systemUserAccount.username=:p1"));
        query3.setParameter("p1", "kenn");
        Staff ce4 = (Staff) query3.getSingleResult();
        c1.setFinanceStaff(ce4);

        //MemberDiscountGroup
        c1.setMemberDiscountGroup(mdgs.get(1));
        c1.setAccumulatedPurchases((double) 65000);
        mdgs.get(1).getCustomers().add(c1);
        //Credit Account
        CreditGroup cg = (CreditGroup) entityManager.createQuery("SELECT g FROM CreditGroup g").getResultList().get(2);
        CreditAccount ca = new CreditAccount();
        ca.setCreditGroup(cg);
        ca.setCustomer(c1);
        ca.setCreditUsed(37000);
        ca.setIsDefault(false);
        cg.getCreditAccounts().add(ca);
        c1.setCreditAccount(ca);

        //Billing Address
        Address billing = new Address();
        billing.setAddressType("Billing");
        billing.setAddressLine1("78 Lodge Manning Drive");
        billing.setZipCode("023423");
        billing.setCity("Chicago");
        billing.setStateName("Illinois");
        billing.setCountry("United States");
        c1.setBillingAddress(billing);

        //Shipping Address
        Address shipping = new Address();
        shipping.setAddressType("Shipping");
        shipping.setAddressLine1("78 Lodge Manning Drive");
        shipping.setZipCode("023423");
        shipping.setCity("Chicago");
        shipping.setStateName("Illinois");
        shipping.setCountry("United States");
        c1.getShippingAddress().add(shipping);

        Address shipping2 = new Address();
        shipping2.setAddressType("Shipping");
        shipping2.setAddressLine1("100 Raligh Drive");
        shipping2.setZipCode("813423");
        shipping2.setCity("Raligh");
        shipping2.setStateName("North Carolina");
        shipping2.setCountry("United States");
        c1.getShippingAddress().add(shipping2);

        entityManager.merge(c1);

    }

    public void createOrderDiscount() {
        //Get Product

        Query query = entityManager.createQuery("SELECT p FROM Product p");
        Product p1 = (Product) query.getResultList().get(0);

        //TODO: testing:
        System.out.println("Testing: size of produect" + query.getResultList().size());

        query = entityManager.createQuery("SELECT p FROM Product p");
        Product p2 = (Product) query.getResultList().get(1);
        query = entityManager.createQuery("SELECT p FROM Product p");
        Product p3 = (Product) query.getResultList().get(2);
        query = entityManager.createQuery("SELECT p FROM Product p");
        Product p4 = (Product) query.getResultList().get(3);

        OrderDiscountGroup odg1 = new OrderDiscountGroup();
        odg1.create(p1, (long) 4800, (double) 0.02);
        OrderDiscountGroup odg2 = new OrderDiscountGroup();
        odg2.create(p1, (long) 7200, (double) 0.03);
        OrderDiscountGroup odg3 = new OrderDiscountGroup();
        odg3.create(p1, (long) 9600, (double) 0.04);

        OrderDiscountGroup odg4 = new OrderDiscountGroup();
        odg4.create(p2, (long) 4800, (double) 0.02);
        OrderDiscountGroup odg5 = new OrderDiscountGroup();
        odg5.create(p2, (long) 7200, (double) 0.03);
        OrderDiscountGroup odg6 = new OrderDiscountGroup();
        odg6.create(p2, (long) 9600, (double) 0.04);

        OrderDiscountGroup odg7 = new OrderDiscountGroup();
        odg7.create(p3, (long) 4000, (double) 0.02);
        OrderDiscountGroup odg8 = new OrderDiscountGroup();
        odg8.create(p3, (long) 6000, (double) 0.03);
        OrderDiscountGroup odg9 = new OrderDiscountGroup();
        odg9.create(p3, (long) 8000, (double) 0.04);

        OrderDiscountGroup odg10 = new OrderDiscountGroup();
        odg10.create(p4, (long) 4000, (double) 0.02);
        OrderDiscountGroup odg11 = new OrderDiscountGroup();
        odg11.create(p4, (long) 6000, (double) 0.03);
        OrderDiscountGroup odg12 = new OrderDiscountGroup();
        odg12.create(p4, (long) 8000, (double) 0.04);

        entityManager.persist(odg1);
        entityManager.persist(odg2);
        entityManager.persist(odg3);
        entityManager.persist(odg4);
        entityManager.persist(odg5);
        entityManager.persist(odg6);
        entityManager.persist(odg7);
        entityManager.persist(odg8);
        entityManager.persist(odg9);
        entityManager.persist(odg10);
        entityManager.persist(odg11);
        entityManager.persist(odg12);
    }

    public void createCreditGroup() {
        CreditGroup g1 = new CreditGroup();
        CreditGroup g2 = new CreditGroup();
        CreditGroup g3 = new CreditGroup();
        CreditGroup g4 = new CreditGroup();
        CreditGroup g5 = new CreditGroup();

        g1.setCreditGroupTitle("Basic");
        g1.setCreditLimitForDs((double) 0);
        g1.setCreditLimitForWs((double) 0);
        g1.setExtensionDays(30);
        g1.setUpgradeLimitForDs((double) 0);
        g1.setUpgradeLimitForWs((double) 0);

        g2.setCreditGroupTitle("Bronze");
        g2.setCreditLimitForDs((double) 12000);
        g2.setCreditLimitForWs((double) 60000);
        g2.setExtensionDays(30);
        g2.setUpgradeLimitForDs((double) 12000);
        g2.setUpgradeLimitForWs((double) 60000);

        g3.setCreditGroupTitle("Silver");
        g3.setCreditLimitForDs((double) 20000);
        g3.setCreditLimitForWs((double) 100000);
        g3.setExtensionDays(30);
        g3.setUpgradeLimitForDs((double) 32000);
        g3.setUpgradeLimitForWs((double) 160000);

        g4.setCreditGroupTitle("Gold");
        g4.setCreditLimitForDs((double) 40000);
        g4.setCreditLimitForWs((double) 200000);
        g4.setExtensionDays(30);
        g4.setUpgradeLimitForDs((double) 72000);
        g4.setUpgradeLimitForWs((double) 360000);

        entityManager.merge(g1);
        entityManager.merge(g2);
        entityManager.merge(g3);
        entityManager.merge(g4);
    }

    private void createMemberDiscountGroup() {
        //Member Discount Group

        MemberDiscountGroup memberDiscountGroup1 = new MemberDiscountGroup();
        memberDiscountGroup1.setGroup("New");
        memberDiscountGroup1.setMemberDiscount((double) 0.0);
        memberDiscountGroup1.setAccSpendingForDs((double) 0.0);
        memberDiscountGroup1.setAccSpendingForWs((double) 0.0);
        mdgs.add(memberDiscountGroup1);
        entityManager.persist(memberDiscountGroup1);

        MemberDiscountGroup memberDiscountGroup2 = new MemberDiscountGroup();
        memberDiscountGroup2.setGroup("Rock");
        memberDiscountGroup2.setMemberDiscount((double) 0.01);
        memberDiscountGroup2.setAccSpendingForDs((double) 25000);
        memberDiscountGroup2.setAccSpendingForWs((double) 75000);
        mdgs.add(memberDiscountGroup2);
        entityManager.persist(memberDiscountGroup2);

        MemberDiscountGroup memberDiscountGroup3 = new MemberDiscountGroup();
        memberDiscountGroup3.setGroup("Emerald");
        memberDiscountGroup3.setMemberDiscount((double) 0.03);
        memberDiscountGroup3.setAccSpendingForDs((double) 75000);
        memberDiscountGroup3.setAccSpendingForWs((double) 125000);
        mdgs.add(memberDiscountGroup3);
        entityManager.persist(memberDiscountGroup3);


        MemberDiscountGroup memberDiscountGroup4 = new MemberDiscountGroup();
        memberDiscountGroup4.setGroup("Diamond");
        memberDiscountGroup4.setMemberDiscount((Double) 0.07);
        memberDiscountGroup4.setAccSpendingForDs((double) 125000);
        memberDiscountGroup4.setAccSpendingForWs((double) 175000);
        mdgs.add(memberDiscountGroup4);
        entityManager.persist(memberDiscountGroup4);
    }

    public ArrayList<MemberDiscountGroup> getMdgs() {
        return mdgs;
    }

    public void setMdgs(ArrayList<MemberDiscountGroup> mdgs) {
        this.mdgs = mdgs;
    }

    private void createFinVP() {
        SecurityRole securityRole = new SecurityRole();
        Staff finVP = new Staff();

        finVP.create("Zhiqi", "Chen", Consts.FIN_DEP);

        ArrayList<AccessRight> accessRights = new ArrayList<AccessRight>();
        AccessRight accessRight1 = new AccessRight();
        accessRight1.create(Consts.VIEW_CREDIT_GROUP, Consts.VIEW_CREDIT_GROUP_PATH, Consts.VIEW_CREDIT_GROUP_CATEGORY);
        accessRights.add(accessRight1);
        AccessRight accessRight2 = new AccessRight();
        accessRight2.create(Consts.MANAGE_CREDIT_GROUP, Consts.MANAGE_CREDIT_GROUP_PATH, Consts.MANAGE_CREDIT_GROUP_CATEGORY);
        accessRights.add(accessRight2);
        // view job list for the whole department
        AccessRight accessRight3 = new AccessRight();
        accessRight3.create(Consts.VIEW_JOB_LIST_ONE_DEP, Consts.VIEW_JOB_LIST_ONE_DEP_PATH, Consts.VIEW_JOB_LIST_ONE_DEP_CATEGORY);
        accessRights.add(accessRight3);

        securityRole.create(Consts.FIN_VP_ROLE, Consts.FIN_DEP);
        securityRole.setAccessRights(accessRights);
        finVP.getSecurityRoles().add(securityRole);
        finVP.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "jinyw9901314@hotmail.com", "adminadmin", "zhiqichen",
                Timestamp.valueOf("2011-09-20 00:22:15"), "What is your favorite color?", "red");
        entityManager.persist(finVP);
    }

    private String convertToDateFormat(Timestamp timeStamp) {
        return formatter.format((java.util.Date) timeStamp);
    }

    private void createPublicHolidays() {
        Calendar cal = Calendar.getInstance();

        //public holidays for 2011
        cal.set(2011, 0, 1, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 1, 3, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 1, 4, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 3, 22, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 4, 1, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 4, 7, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 4, 17, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 7, 9, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 7, 27, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 7, 30, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 9, 26, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 10, 6, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2011, 11, 25, 0, 0, 0);
        createPublicHoliday(cal);

        //public holidays for 2012
        cal.set(2012, 0, 1, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 0, 23, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 0, 24, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 3, 6, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 4, 1, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 4, 5, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 7, 9, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 7, 19, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 9, 26, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 10, 13, 0, 0, 0);
        createPublicHoliday(cal);
        cal.set(2012, 11, 25, 0, 0, 0);
    }

    private void createPublicHoliday(Calendar cal) {
        Timestamp holiday = new Timestamp(cal.getTimeInMillis());
        PublicHoliday ph = new PublicHoliday();
        ph.setDateOfHoliday(holiday);
        entityManager.persist(ph);
    }

    private void createBOMs() {
        int i = 0;
        for (String materialName : Consts.allRawMaterialNames) {
            RawMaterial newMaterial = new RawMaterial(materialName, Consts.rawMaterialLeadTimeList.get(i), Consts.rawMaterialLotSize.get(i));
            newMaterial.setRawMaterialAcronymAndShelfLife();
            BOM bom = new BOM();
            bom.setMaterial(newMaterial);
            bom.getMaterialRequirements().get(0).setValue(dividedBy200(Consts.rawMaterialBoms[i][0]));
            bom.getMaterialRequirements().get(1).setValue(dividedBy200(Consts.rawMaterialBoms[i][1]));
            bom.getMaterialRequirements().get(2).setValue(dividedBy200(Consts.rawMaterialBoms[i][2]));
            bom.getMaterialRequirements().get(3).setValue(dividedBy200(Consts.rawMaterialBoms[i][3]));
            entityManager.merge(bom);
            i++;
        }
    }

    private Double dividedBy200(Double number) {
        return 1.0 * number / 200;
    }

    public void randomizeSalesOrder(int size) {

        // --------------------------- Customer ------------------------------
        Collection<Customer> customersList = entityManager.createQuery("SELECT c FROM Customer c").getResultList();
        ArrayList<Customer> customers = new ArrayList<Customer>();
        // Populate all sales lead into arraylist
        for (Customer c : customersList) {
            customers.add(c);
        }

        //---------------------------- Product ---------------------------------
        Collection<Product> productsList = entityManager.createQuery("SELECT p FROM Product p").getResultList();
        ArrayList<Product> products = new ArrayList<Product>();
        // Populate all products into arraylist
        for (Product p : productsList) {
            products.add(p);
        }

        //---------------------------- Qty Size --------------------------------
        ArrayList<Long> quantities = new ArrayList<Long>();
        for (long x = 50, i = 0; x < 200; x += 20, i++) {
            quantities.add(x);
            if ((i % 2) == 0) {
                quantities.add((long) 0);
            }
        }

        // Create randomizer
        Random rand = new Random();
        int slSize = customers.size();

        // Create random sales order based on size
        for (int i = 0; i < size; i++) {

            // Select random salesLead
            Customer cus = customers.get(rand.nextInt(slSize));

            // Create arraylist of customer address
            Collection<Address> saList = cus.getShippingAddress();
            ArrayList<Address> sa = new ArrayList<Address>();
            for (Address address : saList) {
                sa.add(address);
            }

            // Select random number of Order Lines
            int deliveryOrderNo = (int) ((Math.random() * 2) + 1);

            //Create Sales Quotation for sales lead picked, set all primitive data
            SalesOrder so = new SalesOrder();
            // TODO: for mrp testing: completed, for other: confirmed
            //so.setSalesOrderStatus(Consts.ORDER_FULFILLING);
            so.setSalesOrderStatus(Consts.ORDER_SHIPPED);
            so.setPurchaseOrder(null);
            so.setSalesOrderIdStr(generateSalesOrderId());
            so.setCancelled(false);
            so.setComments("Population data");
            so.setCurrency(Boolean.TRUE);
            // Set Customer - Sales Order
            so.setCustomer(cus);
            cus.getSalesOrders().add(so);

            //Get Staff
            ArrayList<Staff> staffs = new ArrayList<Staff>(cus.getStaffs());
            Staff ce = null;
            for (Staff s : staffs) {
                for (SecurityRole r : s.getSecurityRoles()) {
                    if (r.getRoleName().equals(Consts.SALES_EXECUTIVE_ROLE)) {
                        ce = s;
                    }
                }
            }
            so.setCustomerExecutive(ce);


            // Create random # of order lines
            for (int z = 0; z < deliveryOrderNo; z++) {
                DeliveryOrder ol = new DeliveryOrder();
                ol.setInvoice(null);
                ol.setPurchaseOrder(null);
                ol.setSalesOrder(so);
                ol.setDeliveryOrderIdStr(lcBean.generateDeliveryOrderId());
                ol.setSalesQuotation(null);
                ol.setActive(false);
                ol.setSalesQuotation(null);
                ol.setPurchaseOrder(null);
                ol.setPackingOrder(null);
                ol.setPickingOrder(null);
                ol.setShippingOrder(null);

                //Set status
                ol.setStatus(null);

                //random number
                int a = (int) (Math.random() * (double) sa.size()) + 1;

                // Set random shipping address from customer
                ol.setShippingAddress(sa.get(rand.nextInt(sa.size())));

                // Create itemlines for all products
                for (Product pd : products) {
                    ItemLine il = new ItemLine();
                    il.setProduct(pd);
                    //Set unit price
                    if (cus.getCategory().equals("WholeSale")) {
                        il.setUnitPriceSGD(pd.getWsUnitPrice());
                        il.setUnitPriceUSD(il.getUnitPriceSGD() * ((double) 1 / (double) 1.2));
                    } else {
                        il.setUnitPriceSGD(pd.getDsUnitPrice());
                        il.setUnitPriceUSD(il.getUnitPriceSGD() * ((double) 1 / (double) 1.2));
                    }
                    // Set random qty ordered
                    il.setQtyOrderedCase(quantities.get(rand.nextInt(quantities.size())));
                    il.setQtyOrderedBar(il.getQtyOrderedCase() * 240);

                    // Find order discount using il
                    Query discountQuery = entityManager.createQuery("SELECT d FROM OrderDiscountGroup d WHERE d.product.productType LIKE :p1 AND d.quantity < :p2 ORDER BY d.quantity DESC");
                    discountQuery.setParameter("p1", pd.getProductType());
                    discountQuery.setParameter("p2", il.getQtyOrderedBar());
                    OrderDiscountGroup odg = null;
                    List<OrderDiscountGroup> list = discountQuery.getResultList();
                    if (!list.isEmpty()) {
                        odg = list.get(0);
                    } else {
                        odg = new OrderDiscountGroup();
                        odg.setProduct(il.getProduct());
                        odg.setQuantity(il.getQtyOrderedCase());
                        odg.setOrderDiscount((double) 0.0);
                    }

                    //Set order discount
                    il.setOrderDiscount(odg.getOrderDiscount());

                    //Set subtotal
                    il.setSubTotal((double) il.getUnitPriceSGD() * (double) il.getQtyOrderedBar() * ((double) 1 - (double) il.getMemberDiscount()) * ((double) 1 - (double) il.getOrderDiscount()));

                    // Add item line to order line
                    ol.getItemLines().add(il);
                }

                //Calculate subtotal
                double sb = 0.0;
                for (ItemLine il : ol.getItemLines()) {
                    sb += il.getSubTotal();
                }

                ol.setSubtotal(sb);
                ol.setLeadTime("3 Weeks");
                so.getDeliveryOrders().add(ol);
            }

            double soSubTotal = 0.0;
            //Calculate total
            for (DeliveryOrder ol : so.getDeliveryOrders()) {
                soSubTotal += ol.getSubtotal();
            }
            so.setSubtotal(soSubTotal);
            GlobalVariable tax = gvSession.getGlobalVariableByKey(Consts.GLOBAL_TAX_RATE);
            so.setTax(soSubTotal * tax.getDoubleValue().doubleValue());
            so.setTotal(so.getTax() + so.getSubtotal());

            // Random sales order dates
            int randomDay = 0;
            int randomMonth = 0;
            int randomYear = 0;
            do {
                randomDay = (int) ((Math.random() * 30) + 1);
                randomMonth = (int) ((Math.random() * 12) + 1);
                randomYear = (int) ((Math.random() * 2) + 2010);
            } while (randomYear == 2011 && (randomMonth == 11 || randomMonth == 12));

            String ranDay = "" + randomDay;
            String ranMonth = "" + randomMonth;
            String ranYear = "" + randomYear;
            if (ranDay.length() == 1) {
                ranDay = "0" + ranDay;
            }
            if (ranMonth.length() == 1) {
                ranMonth = "0" + ranMonth;
            }
            Timestamp ts = Timestamp.valueOf(ranYear + "-" + ranMonth + "-" + ranDay + " 13:30:00");
            so.setSalesOrderDate(ts);
            so.setDateStr(so.getSalesOrderDate().toString());

            // Set deliveryOrder to Sales quotation and Sales Quotation to orderline
            entityManager.merge(so);
        }
    }

    private void createProductionPlan() {
        //create salesforecast for 2011 july - dec
        Timestamp currentTime = new Timestamp(Calendar.getInstance().getTime().getTime());
        SalesForecast sf20117 = new SalesForecast(2011, 7, currentTime);
        ArrayList<ArrayList<Long>> previousTotalSales = salesForecastSession.getPreviousTotalSales(2011L, false);
        ArrayList<ArrayList<Long>> previousPromotion = salesForecastSession.getPreviousPromotion(2011L, false);

        for (int i = 0; i < 4; i++) {
            IndivForecast indiv = sf20117.returnProductIndivForecast(i);
            indiv.setCreatedType(Consts.FORECAST_METHOD_HISTORICAL);
            indiv.getHistoricalSF().setYoy(0.01);
            for (int j = 0; j < 6; j++) {
                indiv.getBaseProjectionSelected().get(j).setLongValue(
                        roundToLong((1 + indiv.getHistoricalSF().getYoy()) * (previousTotalSales.get(i).get(j) - previousPromotion.get(i).get(j))));
                indiv.getHumanAdjustList().get(j).setLongValue(0L);
                indiv.getPromotionList().get(j).setLongValue(0L);
                indiv.getFinalValues().get(j).setLongValue(indiv.getBaseProjectionSelected().get(j).getLongValue()
                        + indiv.getHumanAdjustList().get(j).getLongValue() + indiv.getPromotionList().get(j).getLongValue());
            }
        }

        entityManager.merge(sf20117);
        entityManager.flush();

        //sf20117 = salesForecastSession.getSalesForecastFromIdStr(sf20117.getSfIdStr());

        // create sop for 2011 Oct - Dec
        SOP sop201110 = new SOP(2011, 10, currentTime);

        // get sales forecast figure for sop
        for (int i = 0; i < 4; i++) {
            for (int j = 3; j < 6; j++) {
                sop201110.returnProductIndivSOP(i).getSalesforcastValues().get(j - 3).setLongValue(sf20117.returnProductIndivForecast(i).getFinalValues().get(j).getLongValue());
            }
        }

        ArrayList<Long> previousInventories = sopSession.getInventoryOfPrevSeasonLastMonth(sop201110.getStartPeriodYear(), sop201110.getStartPeriodMonth());

        //re -calculate the sop
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 3; j++) {
                Long sfVal = sop201110.returnProductIndivSOP(i).getSalesforcastValues().get(j).getLongValue();
                Long unplanned = sop201110.returnProductIndivSOP(i).getUnplannedDemandList().get(j).getLongValue();
                Long totalDemand = sfVal + unplanned;
                Long inv = sop201110.returnProductIndivSOP(i).getInventoryList().get(j).getLongValue();
                Long prevInventory;
                if (j == 0) {
                    prevInventory = previousInventories.get(i);
                } else {
                    prevInventory = sop201110.returnProductIndivSOP(i).getInventoryList().get(j - 1).getLongValue();
                }
                sop201110.returnProductIndivSOP(i).getUnplannedDemandList().get(j).setLongValue(unplanned);
                sop201110.returnProductIndivSOP(i).getInventoryList().get(j).setLongValue(inv);
                sop201110.returnProductIndivSOP(i).getProductionPlanList().get(j).setLongValue(totalDemand + inv - prevInventory);
            }
        }
        // merge sop
        sopSession.saveMrpSop(sop201110);
        entityManager.flush();

        // create MRP
        for (int counter1 = 10; counter1 < 12; counter1++) {
            // create MRP 2011, 11
            ArrayList<MRP> mrplist = new ArrayList<MRP>();
            int counter = 0;
            for (String materialName : Consts.allRawMaterialNames) {
                MRP nmrp = new MRP(2011, counter1, currentTime, counter);
                nmrp.setBom(mrpSession.getBOM(materialName));
                mrplist.add(nmrp);
                counter++;
            }

            // set gross req and onhand inventory
            int numOfWks;
            ArrayList<ArrayList<Long>> weeklyDemands = mrpSession.getWeeklyDemands(mrplist.get(0).getStartPeriodYear(), mrplist.get(0).getStartPeriodMonth());
            if (weeklyDemands.get(0).get(4) == null) {
                numOfWks = 4;
            } else {
                numOfWks = 5;
            }
            ArrayList<Long> plannedInventory = new ArrayList<Long>();
            ArrayList<Long> plannedReceiptsList = new ArrayList<Long>();
            for (int i = 0; i < 6; i++) {
                plannedInventory.add(0L);
            }
            for (int i = 0; i < 5; i++) {
                plannedReceiptsList.add(0L);
            }
            for (MRP m : mrplist) {
                for (int i = 0; i < numOfWks; i++) {
                    m.getGrossRequirements().add(new IndexNValue(i, new Long(0)));
                    m.getPlannedInventory().add(new IndexNValue(i, new Long(0)));
                    m.getPlannedReceipts().add(new IndexNValue(i, new Long(0)));
                }
                for (int dayId = 0; dayId < numOfWks; dayId++) {
                    // for gross req
                    double sum = 0;

                    for (int i = 0; i < 4; i++) {
                        double kg;
                        if (i == 0 || i == 1) {
                            kg = 12;
                        } else {
                            kg = 13.32;
                        }
                        if (weeklyDemands.get(i).get(dayId) == null) {
                            sum += 0;
                        } else {
                            sum += weeklyDemands.get(i).get(dayId) * kg * m.getBom().getMaterialRequirements().get(i).getValue();
                        }
                    }
                    Long result = Math.round(Math.ceil(sum));
                    m.getGrossRequirements().get(dayId).setLongValue(result);
                }
                // for onhand inventory
                Long prev = mrpSession.getPlannedInventoryForPrevWeek(m.getStartPeriodYear(), m.getStartPeriodMonth(), m.getBom());
                plannedInventory.set(0, prev);
                for (int i = 0; i < numOfWks; i++) {
                    // set planned inventory
                    Long diff = plannedInventory.get(i) + plannedReceiptsList.get(i) - m.getGrossRequirements().get(i).getLongValue();
                    m.getPlannedInventory().get(i).setLongValue(diff);
                    plannedInventory.set(i + 1, diff);
                }
            }

            // to compute all the negative ones with algorithm
            for (MRP m : mrplist) {
                for (int i = 0; i < numOfWks; i++) {
                    Long inv = m.getPlannedInventory().get(i).getLongValue();
                    if (inv < 0) {
                        inv = Math.abs(inv);
                        Long numOfLots;
                        if (inv % m.getBom().getMaterial().getLotSize() == 0) {
                            numOfLots = inv / m.getBom().getMaterial().getLotSize();
                        } else {
                            numOfLots = inv / m.getBom().getMaterial().getLotSize() + 1;
                        }
                        Long prevRec = m.getPlannedReceipts().get(i).getLongValue();
                        Long currentPlannedReceipt = prevRec + numOfLots * m.getBom().getMaterial().getLotSize();
                        m.getPlannedReceipts().get(i).setLongValue(currentPlannedReceipt);

                        for (int j = i; j < numOfWks; j++) {
                            Long prevInv;
                            if (j == 0) {
                                prevInv = mrpSession.getPlannedInventoryForPrevWeek(m.getStartPeriodYear(), m.getStartPeriodMonth(), m.getBom());
                            } else {
                                prevInv = m.getPlannedInventory().get(j - 1).getLongValue();
                            }
                            Long currentInv = prevInv + m.getPlannedReceipts().get(j).getLongValue() - m.getGrossRequirements().get(j).getLongValue();
                            m.getPlannedInventory().get(j).setLongValue(currentInv);
                        }
                    }
                }
            }

            mrpSession.persistNewMrps(mrplist, null);
            entityManager.flush();
        }
    }

    private Long roundToLong(Double d) {
        return Math.round(d);
    }

    private void createTestStaff() {
        Staff testStaff = new Staff();
        testStaff.setFirstName("Test");
        testStaff.setLastName("Staff");

        testStaff.getSystemUserAccount().create(Consts.ACCOUNT_ACTIVATED, "z-ying@comp.nus.edu.sg", "111111", "testman3",
                Timestamp.valueOf("2011-08-29 13:30:00"), "What is your favorite color?", "red");

        entityManager.merge(testStaff);
    }

    private void createCustomerTest() {
        Customer c1 = new Customer();
        c1.setId(new Long(11111));
        c1.setCompanyName("Test Customer");
        c1.setClientId("20110101");
        c1.setCategory("Wholesales");
        c1.setIndustry("Restaurant");
        CreditGroup cg = (CreditGroup) entityManager.createQuery("SELECT g FROM CreditGroup g").getResultList().get(0);
        CreditAccount ca = new CreditAccount();
        ca.setCustomer(c1);
        ca.setCreditGroup(cg);
        ca.setCreditUsed(28990);
        cg.getCreditAccounts().add(ca);
        c1.setCreditAccount(ca);

        entityManager.merge(c1);
    }

    private void createSalesLeadTest() {
        SalesLead s = new SalesLead();
        s.setId(new Long(11112));
        s.setClientId("20110102");
        s.setCategory("DirectSales");
        s.setIndustry("Food");
        entityManager.merge(s);
    }

    private void createClientTest() {
        SalesLead s = new SalesLead();
        s.setId(new Long(11113));
        s.setClientId("20110103");
        s.setCategory("WholeSales");
        s.setIndustry("Hospital");
        entityManager.merge(s);
    }

    private void createTestCreditGroup() {
        CreditGroup g1 = new CreditGroup();

        g1.setId(new Long(999999));
        g1.setCreditGroupTitle("Basic");
        g1.setCreditLimitForDs((double) 0);
        g1.setCreditLimitForWs((double) 0);
        g1.setExtensionDays(30);
        g1.setUpgradeLimitForDs((double) 0);
        g1.setUpgradeLimitForWs((double) 0);


        entityManager.merge(g1);

    }

    private void createCustomerWithNoCa() {
        Customer c1 = new Customer();
        c1.setId(new Long(11115));
        c1.setCompanyName("Customer No CA");

        c1.setCategory("Wholesales");
        c1.setIndustry("Restaurant");
        entityManager.merge(c1);
    }

    private void createSalesForecast() {
        //create salesforecast for 2012 july - dec
        Timestamp currentTime = new Timestamp(Calendar.getInstance().getTime().getTime());
        SalesForecast sf20127 = new SalesForecast(2012, 7, currentTime);
        ArrayList<ArrayList<Long>> previousTotalSales = salesForecastSession.getPreviousTotalSales(2011L, false);
        ArrayList<ArrayList<Long>> previousPromotion = salesForecastSession.getPreviousPromotion(2011L, false);

        for (int i = 0; i < 4; i++) {
            IndivForecast indiv = sf20127.returnProductIndivForecast(i);
            indiv.setCreatedType(Consts.FORECAST_METHOD_HISTORICAL);
            indiv.getHistoricalSF().setYoy(0.01);
            for (int j = 0; j < 6; j++) {
                indiv.getBaseProjectionSelected().get(j).setLongValue(
                        roundToLong((1 + indiv.getHistoricalSF().getYoy()) * (previousTotalSales.get(i).get(j) - previousPromotion.get(i).get(j))));
                indiv.getHumanAdjustList().get(j).setLongValue(0L);
                indiv.getPromotionList().get(j).setLongValue(0L);
                indiv.getFinalValues().get(j).setLongValue(indiv.getBaseProjectionSelected().get(j).getLongValue()
                        + indiv.getHumanAdjustList().get(j).getLongValue() + indiv.getPromotionList().get(j).getLongValue());
            }
        }

        entityManager.merge(sf20127);
        entityManager.flush();

        //sf20117 = salesForecastSession.getSalesForecastFromIdStr(sf20117.getSfIdStr());
//
//         create sop for 2011 Oct - Dec
//        SOP sop201110 = new SOP(2011, 10, currentTime);
//
//         get sales forecast figure for sop
//        for (int i = 0; i < 4; i++) {
//            for (int j = 3; j < 6; j++) {
//                sop201110.returnProductIndivSOP(i).getSalesforcastValues().get(j - 3).setLongValue(sf20117.returnProductIndivForecast(i).getFinalValues().get(j).getLongValue());
//            }
//        }
//
//        ArrayList<Long> previousInventories = sopSession.getInventoryOfPrevSeasonLastMonth(sop201110.getStartPeriodYear(), sop201110.getStartPeriodMonth());
//
//        re -calculate the sop
//        for (int i = 0; i < 4; i++) {
//            for (int j = 0; j < 3; j++) {
//                Long sfVal = sop201110.returnProductIndivSOP(i).getSalesforcastValues().get(j).getLongValue();
//                Long unplanned = sop201110.returnProductIndivSOP(i).getUnplannedDemandList().get(j).getLongValue();
//                Long totalDemand = sfVal + unplanned;
//                Long inv = sop201110.returnProductIndivSOP(i).getInventoryList().get(j).getLongValue();
//                Long prevInventory;
//                if (j == 0) {
//                    prevInventory = previousInventories.get(i);
//                } else {
//                    prevInventory = sop201110.returnProductIndivSOP(i).getInventoryList().get(j - 1).getLongValue();
//                }
//                sop201110.returnProductIndivSOP(i).getUnplannedDemandList().get(j).setLongValue(unplanned);
//                sop201110.returnProductIndivSOP(i).getInventoryList().get(j).setLongValue(inv);
//                sop201110.returnProductIndivSOP(i).getProductionPlanList().get(j).setLongValue(totalDemand + inv - prevInventory);
//            }
//        }
//         merge sop
//        sopSession.saveMrpSop(sop201110);
//        entityManager.flush();
//
//         create MRP
//        for (int counter1 = 10; counter1 < 13; counter1++) {
//             create MRP 2011, 11
//            ArrayList<MRP> mrplist = new ArrayList<MRP>();
//            int counter = 0;
//            for (String materialName : Consts.allRawMaterialNames) {
//                MRP nmrp = new MRP(2011, counter1, currentTime, counter);
//                nmrp.setBom(mrpSession.getBOM(materialName));
//                mrplist.add(nmrp);
//                counter++;
//            }
//
//             set gross req and onhand inventory
//            int numOfWks;
//            ArrayList<ArrayList<Long>> weeklyDemands = mrpSession.getWeeklyDemands(mrplist.get(0).getStartPeriodYear(), mrplist.get(0).getStartPeriodMonth());
//            if (weeklyDemands.get(0).get(4) == null) {
//                numOfWks = 4;
//            } else {
//                numOfWks = 5;
//            }
//            ArrayList<Long> plannedInventory = new ArrayList<Long>();
//            ArrayList<Long> plannedReceiptsList = new ArrayList<Long>();
//            for (int i = 0; i < 6; i++) {
//                plannedInventory.add(0L);
//            }
//            for (int i = 0; i < 5; i++) {
//                plannedReceiptsList.add(0L);
//            }
//            for (MRP m : mrplist) {
//                for (int i = 0; i < numOfWks; i++) {
//                    m.getGrossRequirements().add(new IndexNValue(i, new Long(0)));
//                    m.getPlannedInventory().add(new IndexNValue(i, new Long(0)));
//                    m.getPlannedReceipts().add(new IndexNValue(i, new Long(0)));
//                }
//                for (int dayId = 0; dayId < numOfWks; dayId++) {
//                     for gross req
//                    double sum = 0;
//
//                    for (int i = 0; i < 4; i++) {
//                        double kg;
//                        if (i == 0 || i == 1) {
//                            kg = 12;
//                        } else {
//                            kg = 13.32;
//                        }
//                        if (weeklyDemands.get(i).get(dayId) == null) {
//                            sum += 0;
//                        } else {
//                            sum += weeklyDemands.get(i).get(dayId) * kg * m.getBom().getMaterialRequirements().get(i).getValue();
//                        }
//                    }
//                    Long result = Math.round(Math.ceil(sum));
//                    m.getGrossRequirements().get(dayId).setLongValue(result);
//                }
//                 for onhand inventory
//                Long prev = mrpSession.getPlannedInventoryForPrevWeek(m.getStartPeriodYear(), m.getStartPeriodMonth(), m.getBom());
//                plannedInventory.set(0, prev);
//                for (int i = 0; i < numOfWks; i++) {
//                     set planned inventory
//                    Long diff = plannedInventory.get(i) + plannedReceiptsList.get(i) - m.getGrossRequirements().get(i).getLongValue();
//                    m.getPlannedInventory().get(i).setLongValue(diff);
//                    plannedInventory.set(i + 1, diff);
//                }
//            }
//
//             to compute all the negative ones with algorithm
//            for (MRP m : mrplist) {
//                for (int i = 0; i < numOfWks; i++) {
//                    Long inv = m.getPlannedInventory().get(i).getLongValue();
//                    if (inv < 0) {
//                        inv = Math.abs(inv);
//                        Long numOfLots;
//                        if (inv % m.getBom().getMaterial().getLotSize() == 0) {
//                            numOfLots = inv / m.getBom().getMaterial().getLotSize();
//                        } else {
//                            numOfLots = inv / m.getBom().getMaterial().getLotSize() + 1;
//                        }
//                        Long prevRec = m.getPlannedReceipts().get(i).getLongValue();
//                        Long currentPlannedReceipt = prevRec + numOfLots * m.getBom().getMaterial().getLotSize();
//                        m.getPlannedReceipts().get(i).setLongValue(currentPlannedReceipt);
//
//                        for (int j = i; j < numOfWks; j++) {
//                            Long prevInv;
//                            if (j == 0) {
//                                prevInv = mrpSession.getPlannedInventoryForPrevWeek(m.getStartPeriodYear(), m.getStartPeriodMonth(), m.getBom());
//                            } else {
//                                prevInv = m.getPlannedInventory().get(j - 1).getLongValue();
//                            }
//                            Long currentInv = prevInv + m.getPlannedReceipts().get(j).getLongValue() - m.getGrossRequirements().get(j).getLongValue();
//                            m.getPlannedInventory().get(j).setLongValue(currentInv);
//                        }
//                    }
//                }
//            }
//
//            mrpSession.persistNewMrps(mrplist, null);
//            entityManager.flush();
//        }
    }
}
